Flask app getting 0x8007000d error with IIS - flask

I'm trying to get a very basic flask app to work on IIS 10 running on Windows Server 2019.
I followed the HTTPPlatform Handler instructions from: https://learn.microsoft.com/en-us/visualstudio/python/configure-web-apps-for-iis-windows?view=vs-2019
But I keep getting HTTP 500.19 errors with error code 0x8007000d. From googling, I suspect the problem is in my web.config, but I don't know what is wrong. The app works fine from the command line.
This is my web.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="PythonHandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified"/>
</handlers>
<httpPlatform processPath="D:\python39\python.exe"
arguments="D:\inetpub\wwwroot\flasktest.py"
stdoutLogEnabled="true"
stdoutLogFile="d:\logs\python.log"
startupTimeLimit="60"
processesPerApplication="16">
<environmentVariables>
<environmentVariable name="SERVER_PORT" value="9010" />
</environmentVariables>
</httpPlatform>
</system.webServer>
</configuration>
This is my app.py:
from flask import Flask, render_template
app = Flask(__name__)
#app.debug = True
#app.route("/", methods=('GET', 'POST'))
def home():
return render_template('main.html', hello = 'hello world')
if __name__ == '__main__':
app.run(host='0.0.0.0',port=9010)
this is my main.html
{% extends 'layout.html' %}
{% block content %}
<div class="container">
<div class="leftrow1">
{{ hello }}
</div>
<div class="leftrow2">
</div>
<div class="leftrow3">
</div>
<div class="leftrow4">
</div>
<div class="main_frame_1">
</div>
<div class="main_frame_2">
</div>
</div>
{% endblock content %}
and this is the layout.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="/static/css/style.css"/>
</head>
<body>
{% block content %}
{% endblock content %}
</body>
Update: based on comments received, adding additional error info
This is the error I get (without installing httpplatformhandler), nothing is in eventlog when this occurs:
This is the error I get after installing httpplatformhandler:
with the 500.3 message, I also get a bunch of event 1000 from HttpPlatformHandler in event log:

It seems that you don't have the correct permission to access D:\python39\python.exe and D:\inetpub\wwwroot\flasktest.py.
Open IIS Manager -> Select the site you added the HttpPlatformHandler
Click Handler Mappings in the feature view -> select the HttpPlatformHandler
Click Edit Feature Permission in the Action Panel
Make sure you have check the Execute permission

Related

Django Bootstrap Carousel wont ride

This is my first project with building a website. I have been following these tutorials. I browsed through the Bootstrap components page and found a Carousel method (slides only) that I wanted to use. I copied and pasted it into my code. The first image shows up which is correct, because it is active, but the Carousel does not slide to the next image. The first code block shows a summed up version. The second block of code is after running python manage.py runserver. The third block of code is when I open the IP address link. I am not sure what I am doing wrong. Any suggestions? Let me know if you need some more information.
<!DOCTYPE html>
<html lang="en">
<head>
<title>AeroTract</title>
<meta charset="utf-8" />
{% load static %}
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}" type = "text/css"/>
<meta name="viewport" content = "width=device-width, initial-scale=1.0">
<style type="text/css">
html,
body {
height:100%
}
</style>
</head>
<body class="body" style="background-color:#FFF8DC"> <!-- Main page background color -->
<div class="container-fluid" style="min-height:95%; "> <!-- Footer Height -->
<div class="row">
<div class = "col-sm-2"> </div>
<div class="col-sm-8">
<br>
<div id="mainCarousel" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<img class="d-block w-100" src="{% static 'img/Forestry.png' %}" alt="First slide">
</div>
<div class="carousel-item">
<img class="d-block w-100" src="{% static 'img/Agricultural.png' %}" alt="Second slide">
</div>
<div class="carousel-item">
<img class="d-block w-100" src="{% static 'img/Industrial.png' %}" alt="Third slide">
</div>
</div>
</div>
<br>
</div>
</div>
</div>
</body>
</html>
(base) C:\Users\name\PycharmProjects\Django_tutorials\mysite>python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
May 07, 2020 - 14:46:06
Django version 3.0.6, using settings 'mysite.settings'
Starting development server at http://#########/
Quit the server with CTRL-BREAK.
[07/May/2020 14:46:42] "GET / HTTP/1.1" 200 3408
You are only including the css from bootstrap. I believe you also need the javascript.
You may want to add the these scripts:
https://getbootstrap.com/docs/4.4/getting-started/introduction/#js
In my experience popper.js.min file was apparently clashing with bootstrap. Disabling that solved the problem.

flask application http request method showing error

so I was studying flask and how to request http methods.I am able to run html.But when i request url they are showing error.please guide me.code is attached herewith.Thanks in advance.
<html>
<head> sub </head>
<body>
<form action="http://localhost:5000/submit",method="path">
<p>Enter name</p>
<p> <input type="text",name="nm" /> </p>
<p><input type="submit",value="submit" /></p>
</form>
</body>
</html>
from flask import Flask,url_for,redirect,request
app=Flask(__name__)
#app.route('/page/<name>')
def display(name):
return 'Hello %s'%name
#app.route('/submit',methods=['POST','GET'])
def submit():
if request.methods=='POST':
user=request.form['nm']
return redirect(url_for('display',name=user))
else:
user=request.args.get('nm')
return redirect(url_for('display',name=user))
if __name__=='__main__':
app.run(debug=True)
Use url_for template tag for mentioning url in html and also method should be POST and remove those , in your html.
<form action="{{ url_for('sumbit') }}" method="POST">
Always .format for string operations
return "Hello {}".format(name)

usinig Django urls in react, is_authenticated in react, displaying context in react

So, I've got 3 questions
How to use Django's URLs in react
EXAMPLE:
index.js (in react)
<Router>
<div>
<nav className="navbar navbar-inverse bg-inverse">
<div className="container">
<Link to="/" className="navbar-brand">PetFinder</Link>
<Link to="/storage" className="navbar-brand">Storage </Link>
Sign-Up <== like this
</div>
</nav>
<Route exact path={"/"} component={PetRegistration} />
<Route path={"/storage"} render={() => <Storage ids={checkingName} />} />
</div>
</Router>
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
#path('api-auth/', include('rest_framework.urls', namespace="rest_framework")),
path('api/animals/', include('petsite.urls', namespace='petsite')),
path('api/user_info', core_views.UserInfo.as_view()),
path('signup/', core_views.signup, name='signup'),
path('', csrf_exempt(core_views.index), name='index'),
path(r'^login/$', auth_views.login, name='login'),
]
is_authenticated in react
How I did it:
In index.html
I wrote this ******. I am ashamed of this. Don't judge me, okay just a bit...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<!--
manifest.json provides metadata used when your web app is added to the
homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div class="signUpBlock">
Sign-Up
</div>
<div id="root">
</div>
<span class="currentUser" style="display: none">{{user.id}}</span>
<span class="currentUserName" style="display: none">{{user.username}}</span>
<span id="DJANGO_USER" style="display: none"></span>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
<script type="text/javascript">
var WHETHER_DJANGO_USER_IS_AUTH = "{{user.is_authenticated|yesno:"true,false"}}";
document.getElementById("DJANGO_USER").innerHTML = WHETHER_DJANGO_USER_IS_AUTH;
</script>
</body>
</html>
Check the code below:
<script type="text/javascript">
var WHETHER_DJANGO_USER_IS_AUTH = "{{user.is_authenticated|yesno:"true,false"}}";
document.getElementById("DJANGO_USER").innerHTML = WHETHER_DJANGO_USER_IS_AUTH;
</script>
<span id="DJANGO_USER" style="display: none"></span>
AND THEN IN index.js I do this
let boolButString = $('#DJANGO_USER').text()
var StringToBool = (boolButString === 'true');
If StringToBool = true I do smth (means that user is logged in)
else StringToBool != true I do smth (means that user is not logged in)
if (StringToBool) {
do smth
} else {
make some tea for him
}
I don't think I did it in a right way can you suggest me smth?
Is it real to check whether a user is auth. or not?
How to display Django context in react.
You might have seen how I did it in index.html
As usual, I wrote:
def index(request):
return render(request, 'index.html', {
"user" : request.user,
})
end then
<span class="currentUser" style="display: none">{{user.id}}</span>
grab data through jquery and display it in react app.
What can you suggest me?
How to display context properly?
Sry for cups.

Stuck with Test-Driven Development with Python (chapter 6) [duplicate]

I'm writing my first Django app by following along with this book:
http://chimera.labs.oreilly.com/books/1234000000754/ch05.html#_passing_python_variables_to_be_rendered_in_the_template
In the book there is a test that is verifying that the html is being returned as it is supposed to. Here is the test:
def test_home_page_returns_correct_html(self):
request = HttpRequest()
response = home_page(request)
expected_html = render_to_string('home.html')
print(expected_html)
print(response.content.decode())
self.assertEqual(response.content.decode(), expected_html)
My test is failing on the assertEqual test because I have added a csrf token in my HTML using the Django Template Language. Here is what my HTML page looks like:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>To-Do lists</title>
</head>
<body>
<h1>Your To-Do list</h1>
<form method="POST">
<input name="item_text" id="id_new_item" placeholder="Enter a to-do item"/>
{% csrf_token %}
</form>
<table id="id_list_table">
<tr><td>{{ new_item_list }}</td></tr>
</table>
</body>
</html>
My assert is failing due to the render_to_string method not including the token. Here is what my two print statements included in my test print out:
F<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>To-Do lists</title>
</head>
<body>
<h1>Your To-Do list</h1>
<form method="POST">
<input name="item_text" id="id_new_item" placeholder="Enter a to-do item"/>
</form>
<table id="id_list_table">
<tr><td></td></tr>
</table>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>To-Do lists</title>
</head>
<body>
<h1>Your To-Do list</h1>
<form method="POST">
<input name="item_text" id="id_new_item" placeholder="Enter a to-do item"/>
<input type='hidden' name='csrfmiddlewaretoken' value='VAiGvXZLHCjxWEWdjhgQRBwBSnMVoIWR' />
</form>
<table id="id_list_table">
<tr><td></td></tr>
</table>
</body>
</html>
F.
He doesn't have this problem in the book (he's using 1.8), so I was wondering if the method behavior has changed, or how I would write this test to pass.
The request argument was added to render_to_string in Django 1.8. You could try changing the line in your test to:
expected_html = render_to_string('home.html', request=request)
It's only required to make this change in Django 1.9+, the test passes without the request in Django 1.8.
I found this solution which has worked for the latest Django version - 3.0.6
#add a function to the post request test function
def remove_csrf_tag(text):
"""Remove csrf tag from TEXT"""
return re.sub(r'<[^>]*csrfmiddlewaretoken[^>]*>', '', text)
...
# then change assertion
def test_home_page_can_save_a_POST_request(self):
...
self.assertEqual(
remove_csrf_tag(response.content),
remove_csrf_tag(expected_html)
)

Django unit testing: assertEqual() fails

I am following the book "Test-Driven Development in Python" and have the following functions:
tests.py:
def testHomePageCanSaveAPostRequest(self):
request = HttpRequest()
request.method = 'POST'
request.POST['itemText'] = 'A new list item'
response = homePage(request)
if response:
response = response.content.decode('UTF-8')
self.assertIn('A new list item', response)
expectedHTML = render(request, 'lists/home.html', {'itemText':'A new list item'})
if expectedHTML:
expectedHTML = expectedHTML.content.decode('UTF-8')
print(response)
print(expectedHTML)
if response==expectedHTML:
print('Same')
self.assertIn('A new list item', expectedHTML)
self.assertEqual(response, expectedHTML)
views.py
def homePage(request):
print(request.POST.get('itemText'))
return render(request, 'lists/home.html', {'itemText':request.POST.get('itemText')})
home.html:
...
<form method=POST>
<input id=newItem name=itemText placeholder="Enter a to-do item">
</form>
<table id=listTable>
<tr><td>{{itemText}}</td></tr>
</table>
...
Both assertIn(..., response) and assertIn(..., expectedHTML) are successful, which means both response and expectedHTML have 'A new list item' in them.
I also print out response and expectedHMTL, and they look exactly the same. The comparison also print out 'Same' showing that they are the same.
However, the assertEqual fails with the following line by line comparison:
...
<table id=listTable>
- <tr><td>None</td></tr>
? ----
+ <tr><td></td></tr>
</table>
...
One is None and the other is empty.? What did I do wrong?
EDIT:
The entire test output is listed in the following:
Creating test database for alias 'default'...
A new list item
<!doctype html>
<html>
<head>
<title>To do list</title>
<meta charset=utf-8>
</head>
<body>
<h1>Your to do list</h1>
<form method=POST>
<input id=newItem name=itemText placeholder="Enter a to-do item">
</form>
<table id=listTable>
<tr><td>A new list item</td></tr>
</table>
</body>
</html>
<!doctype html>
<html>
<head>
<title>To do list</title>
<meta charset=utf-8>
</head>
<body>
<h1>Your to do list</h1>
<form method=POST>
<input id=newItem name=itemText placeholder="Enter a to-do item">
</form>
<table id=listTable>
<tr><td>A new list item</td></tr>
</table>
</body>
</html>
Same
.None
F.
======================================================================
FAIL: testHomePageReturnsCorrectHTML (lists.tests.HomePageTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/yltang/course/TDD/lecture/python/webapps/git/superlists/superlists/lists/tests.py", line 27, in testHomePageReturnsCorrectHTML
self.assertEqual(response, expectedHTML)
AssertionError: '<!do[231 chars]stTable>\n <tr><td>None</td></tr>\n</table>\n</body>\n</html>' != '<!do[231 chars]stTable>\n <tr><td></td></tr>\n</table>\n</body>\n</html>'
<!doctype html>
<html>
<head>
<title>To do list</title>
<meta charset=utf-8>
</head>
<body>
<h1>Your to do list</h1>
<form method=POST>
<input id=newItem name=itemText placeholder="Enter a to-do item">
</form>
<table id=listTable>
- <tr><td>None</td></tr>
? ----
+ <tr><td></td></tr>
</table>
</body>
</html>
----------------------------------------------------------------------
Ran 3 tests in 0.017s
FAILED (failures=1)
Destroying test database for alias 'default'...
You have added the print statements to a different test. The print statements are in testHomePageCanSaveAPostRequest, which is passing.
The failing test is testHomePageReturnsCorrectHTML, which you have not included in your question.