I'm developing a Flask website using Visual Studio 2013's PythonTools, which has its own debugger, and that allows me to step through the initial setup code, up until app.run()
However the code I want to debug is the routing code, like this:
#app.route('/')
def url_index():
return render_template('index.html')
I know that function is running because the server does respond with index.html, but if I put a breakpoint on the last line, it'll never get hit.
Is there any way to debug these routing functions? Flask says it comes with a debugger but how do I use it? Will it be compatible with Visual Studio?
For the Flask debugger, you can set app.debug to True:
app.debug = True
or
app.run(debug=True)
And then:
#app.route('/')
def index():
raise
return render_template('index.html')
And then you can debug the function with the Flask debugger in your browser.
6 months later, and while it still doesn't look possible to automatically debug URL routing in flask, you can manually attach a debugger to the flask process, though you'll have to re-add it if you restart the server or if the auto-reloader detects changes in your .py files and restarts.
Just go:
Tools -> Attach to Process
and select the Python.exe that is not greyed out (that's the initial flask code that visual studio is already debugging), and then do something that would cause the breakpoint to be hit (e.g. reload the page), and you should have success.
Sadly the current version of PTVS doesn't support Flask projects.
Good thing is: the already released PTVS 2.1 alpha does: http://pytools.codeplex.com/wikipage?title=Flask
You can turn off reloading with debug mode by using
app.run(debug=True, use_reloader=False)
The Flask error handling docs go into the details of the debugging options.
Related
I am extremely new to flask framework. I wrote a few basic beginner codes in flask and after I did the changes to it, the output doesn't change as is the same code is running behind the scene which I can't figure out.
I Tried:-
Changing the directory of my python file.
Deleting the file and made a new one.
Deleting the browser cache and cookies.
This seems to be a common issue but there's no perfect answer for this question on this site, please help.
Sample code:
from flask import Flask , redirect , url_for, render_template
app = Flask(__name__)
#app.route("/")
def home():
return "Hello bc"
if __name__ == "__main__":
app.run()
I opened the task manager to check if there was any process related to the flask running in the background and ended up closing all the python processes that were running in the background and it's working fine now thanks for the replies.
first of all enable the debug true that helps
app.run(debug=True)
This will display flask restarting in the terminal when you update the code.
Second, try hard refresh of the browser by pressing CTRL+SHIFT+R
For sake of better coding and work with flask in future id suggest you setting up venv variablies like FLASK_APP=app.py , FLASK_DEBUG=1. And using flask run in your terminal.
Im not sure wich OS you are using on windows u can use set FLASK_DEBUG=1 , on linux just replace set with export FLASK_DEBUG=1.
I am attempting to teach myself flask from Medium and YouTube tutorials, and keep running into the same error.
Screenshot of 404 Not Found
Normally, I would assume I messed up, made a spelling mistake, and shouldn't embarrass myself by asking how to fix it on a public forum, but I literally copy-pasted the code without making any changes.
I found a Medium post that walks you through step-by-step with simple instructions and ran the code
from flask import Flask # import flask
app = Flask(__name__) # create an app instance
#app.route("/") # at the end point /
def hello(): # call method hello
return "Hello World!" # which returns "hello world"
if __name__ == "__main__": # on running python app.py
app.run() # run the flask app
and continue to get the same error. Does anyone know what I'm doing wrong?
Screenshot of Pycharm
Can you try changing app.run() to app.run(debug=True) and then restart the server?
Also, after restarting try visiting the link in incognito just to make sure it's not a caching issue.
As Medium explains further on in that tutorial:
For development purposes, we use something called as debug mode. When debug=True is set the server restarts as we add new code to our Flask Application.
So, I tried all of these and nothing worked. Then I restarted the computer and it still didn't work. And then I restarted is 2 more times and it worked, so I don't know what happened.
I am trying to diagnose some mysterious Internal Server Errors, so I added logging to the flask app. After digging through many explanations, I found this answer which I am using below, along with the suggestion to put everything inside a #app.before_first_request decorator.
Locally this works as expected and werkzeuglog.log contains exactly what is printed to the screen.
But on the server:
The log file is created.
Nothing is written to it.
No errors are thrown, at least not to the user
#app.before_first_request
def initialize():
logger = logging.getLogger('werkzeug')
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler('werkzeuglog.log')
logger.addHandler(handler)
if __name__ == '__main__':
#run app
app.run(
host="0.0.0.0",
port=int("80"),
debug=False
)
Am I doing something wrong or is this some server issue that is beyond my scope? Gentle answers appreciated!
EDIT:
Some context: An internal server error is caused when the user uploads a file and I am trying to figure out what's going wrong using the log.
I don't think it can be an issue with permissions since the script definitely creates the file. I checked that the disk is not full.
EDIT 2
I reran the run.fcgi file which starts the WSGI Server. Now the manual entries to the log file via logger.info('blah blah') show up but not the others i.e. GET POST etc.
I don't have access to /var/log/nginx. It's a student-volunteer run server so I would like to give them as much info as I can. But this is all I have so far.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I built a little web app in Flask and am trying to deploy it on Pythonanywhere.
During development, I used a local server and launch my app as such:
if __name__ == '__main__':
app.run(debug=True,extra_files=['./static/results.csv',])
results.csv serves as a tiny database (I don't need more) and everytime a line is added to the file, from a Flask form submition, the app is releaded. I then get:
Detected change in '/Users/rodolphegonzales/sync/Survey/app/static/results.csv', reloading
Once I deploy on Pythonanywhere, this doesn't work anymore. when I run:
if __name__ == '__main__':
app.run(debug=False,extra_files=['./static/results.csv',])
I get:
Internal Server Error. The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
Looking at the log, this is due to the fact that the changes in results.csv weren't detected, and that the app wasn't reloaded.
How to properly detect changes in extra files when deploying a Flask app?
EDIT: file change detection and reload is apparently impossible to do outside of the debug mode. A touch to the WSGI should automatically reload, I'll try it out.
This has nothing to do with the reloader (well, at least not the way you think). PythonAnywhere runs a WSGI server for you, pointed at your app. If you call the dev server unconditionally, it will block and PythonAnywhere's server will never pick it up.
Move the call to the dev server inside a __name__ guard.
if __name__ == '__main__':
app.run(...)
You should not reload an app automatically in production (and based on the way PythonAnywhere works, you wouldn't be able to, you need to manually reload). Based on what you've described, you shouldn't need to reload it at all, just re-read the static file when you need to get data. Given that most WSGI servers run in multiple processes, you're probably at risk of corrupting your simple file by writing to it from multiple processes at once. This is why you use a database.
Ok, my little knowledge of how this works in deployment confused me. it turns out I can't, outside of development using debug = True, and to the best of my knowledge, automatically observe changed files and reload the app through an argument in app.run(...). A solution is to "touch" Pythonanywhere's wsgi file anytime another form is submitted (in which case the app is reloaded). I'm doing it like this:
import os
os.utime('/var/www/USERNAME_pythonanywhere_com_wsgi.py', None)
This seems to do the trick. Thanks for your help!
I am using Flask on Dreamhost. I (mostly) followed the instruction posted here https://mattcarrier.com/flask-dreamhost-setup/. I was able to successfully set up pages and direct urls to those pages, etc.
Now I want to be able to set a 404 page. I set the error handler using #app.errorhandler. The only problem is that it just returns a standard Apache 500 error page if I go to any page that doesn't have a URL set. Is this because of how Dreamhost has Apache setup? The public (static) folder is at the top level. How can I fix this?
You may want to try creating the file "missing.html" at the top level.
source: http://wiki.dreamhost.com/Creating_custom_error_pages
Edit:
To setup an error handling page from Flask itself, you do this:
from flask import render_template
#app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
See: http://flask.pocoo.org/docs/patterns/errorpages/
My thought is that you are getting the 500 error because Flask/Python is crashing. Do you have debugging turned on? How is your routing setup?
I found the answer here - http://blog.tuxcoder.com/2011/9/8/dreamhost_python_wsgi/
If you plan to do any active development on the Dreamhost side, this step will simplify your efforts. Werkzeug comes with a really nice debugging engine, but it does not work with the Dreamhost configuration by default.
or example, if you have a simple Python coding error in your app, it will result in the following:
In this mode, you're out of luck. The only option is to startup a local server where you can go back and test the app. In some cases it might be a big effort just to replicate the bug.
With the Werkzeug Debugger enabled and patched, you'll get a much nicer output:
Here is what it says on the Dreamhost Wiki http://wiki.dreamhost.com/Flask (in passenger_wsgi.py:
# Uncomment next two lines to enable debugging
# from werkzeug.debug import DebuggedApplication
# application = DebuggedApplication(application, evalex=True)