Flask 404 on Dreamhost - python

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)

Related

Updated index.html not showing in browser

I have a very simple python Flask app. It is just an app.py and a templates/index.html. It is deployed in Azure. The problem is that when I make changes to the index.html and re-deploy it, the browser still loads the old one although I can see the new index.html on the server. I have tried Azure Web App Service stop/start to no success.
Any ideas how to fix this?
The file is probably still cached by your browser. Try to reload the site without cache (Different for every browser and OS - shift+f5 windows, cmd+r mac etc., ...).
You can set an HTTP-Header to control how long files are cached.
I'd recommend using the #app.after_request decorator.
#app.after_request
def add_header(response):
response.cache_control.max_age = 300 # set this to 0 to force a reload every time
return response
I hope that helps. If not, please provide a little bit more code.

Is it possible to get flask app url without request context?

It's a URL shortener app. The app structure is like following:
App structure
In forms.py, I have custom validators: validate_url() and validate_short_url()
that use APP_URL; APP_URL = "localhost:5000/"
I'm fine with that running locally, but there is a lot of cases app domain can change:
Running through docker image;
Hosting (e.g. on Heroku);
Changing the port value;
So every time I run this flask app differently I have to change the value of APP_URL, which isn't the best practice
All in all, I want to use something like flask.Request.url_root to avoid manual writing again and again
When I just try to use flask.request I get the following traceback:
RuntimeError: Working outside of request context.
This typically means that you attempted to use functionality that needed
an active HTTP request. Consult the documentation on testing for
information about how to avoid this problem.
forms.py is posted here
The app is already hosted on Heroku, here is the link: https://qysqa.herokuapp.com/
The solution was to use flask.request inside custom validators (validate_url() and validate_short_url()) where app context gets passed

Sessions always empty with flask / heroku

I'm having an issue with my application on Heroku where sessions aren't persisting. Specifically, flask's SecureCookieSession object is empty, every time a request is made. Contrast this with running my application on localhost, where the contents of SecureCookieSession persist the way they should.
Also I'm using flask-login + flask-seasurf, but I'm pretty sure the issue happening somewhere between flask / gunicorn / heroku.
Here are three questions that describe a similar issue:
Flask sessions not persisting on heroku
Flask session not persisting
Flask-Login and Heroku issues
Except I'm not dealing with AJAX or multiple workers here (it's a single heroku free dyno, with a single line in the Procfile). I do get the feeling that using server side sessions with redis or switching from Heroku to something like EC2 might solve my problem though.
Also, here's my git repo if it helps https://gitlab.com/collectqt/quirell/tree/develop. And I'm testing session stuff with
def _before_request(self):
LOG.debug('SESSION REQUEST '+str(flask.session))
def _after_request(self, response):
LOG.debug('SESSION RESPONSE '+str(flask.session))
return response
Got the solved with some external help, mainly by changing the secret key to use a random string I came up with, instead of os.urandom(24)
Changing to server side redis sessions helped too, if only by making testing simpler
Just in case someone else comes across this question, check APPLICATION_ROOT configuration variable. I recently deployed a Flask application to a subdirectory under nginx with a reverse-proxy and setting the APPLICATION_ROOT variable broke Flask's session. Cookies aren't being set under the correct path because of that.

How do you debug url routing in Flask?

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.

How to make URL routing execute after StaticMiddleware in web.py

I have a URL route in my web.py application that I want to run to catch all URLs that hit the server, but only after any static assets are served.
For example, if theres is js/test.js in my static directory, the path http://a.com/js/tests.js should return the file contents. But I also have my url routing set up so that there is a regex that catches everything like this:
urls = ('/.*', 'CatchAllHandler')
So this should run only if no static asset was discovered. A request for http://a.com/js/test.js should return the static file test.js, but a request for http://a.com/js/nope.js should route through the CatchAllHandler.
I've looked into writing my own StaticMiddleware for this, but it will only help if the order of web.py operations is changed. Currently the middleware is executed after the URL routes have been processed. I need the middleware to run first, and let the url routing clean up the requests that were not served static assets.
The one idea I have is to use the notfound() function as my catch all handler, but that may not be best.
the url matching is python regex. You can test/play with python regex here
that said, this should work for you:
('/(?!static)(.*)', 'CatchAllHandler')
I haven't played with web.py's middleware, but my understanding.. WSGI middleware happens before web.py gets to seeing the request/response. I would think, provided your WSGI MiddleWare is properly configured, it would just work.
pouts That sucks. There is the hook stuff, which makes it really easy, I've don't that before, and it will see all the stuff before .. docs are here: http://webpy.org/cookbook/application_processors
but I guess in regards to your other comment, 'wanting it to work regardless of URL'. How would you know it's static content otherwise? I'm confused greatly. The EASIEST way, since for production you want some other web server running your web.py scripts, is to push all the static content into the web server. Then you can of course do whatever you want in the web server that needs doing. This is exactly what happens with mod_wsgi and apache for instance (you change /static to point to the directory IN the web server).
Perhaps if you shared an actual example of what you need done, I could help you more. Otherwise I've given you now 3 different ways to handle the problem (excluding using WSGI middleware). How many more do you need? :P

Categories