Questions tagged [flask]
Flask is a lightweight framework for developing web applications using Python.
4,472
questions
807
votes
24
answers
1.0m
views
How to serve static files in Flask
So this is embarrassing. I've got an application that I threw together in Flask and for now it is just serving up a single static HTML page with some links to CSS and JS. And I can't find where in the ...
1253
votes
25
answers
1.8m
views
Get the data received in a Flask request
I want to be able to get the data sent to my Flask app. I've tried accessing request.data but it is an empty string. How do you access request data?
from flask import request
@app.route('/', methods=...
168
votes
4
answers
85k
views
Are global variables thread-safe in Flask? How do I share data between requests?
In my application, the state of a common object is changed by making requests, and the response depends on the state.
class SomeObj():
def __init__(self, param):
self.param = param
def ...
119
votes
2
answers
373k
views
Sending data from HTML form to a Python script in Flask
I have the code below in my Python script:
def cmd_wui(argv, path_to_tx):
"""Run a web UI."""
from flask import Flask, flash, jsonify, render_template, request
import webbrowser
app = ...
693
votes
18
answers
783k
views
Configure Flask dev server to be visible across the network
I'm not sure if this is Flask specific, but when I run an app in dev mode (http://localhost:5000), I cannot access it from other machines on the network (with http://[dev-host-ip]:5000). With Rails in ...
674
votes
15
answers
881k
views
Return JSON response from Flask view
I have a function that analyzes a CSV file with Pandas and produces a dict with summary information. I want to return the results as a response from a Flask view. How do I return a JSON response?
@...
498
votes
13
answers
847k
views
How to get POSTed JSON in Flask?
I'm trying to build a simple API using Flask, in which I now want to read some POSTed JSON. I do the POST with the Postman Chrome extension, and the JSON I POST is simply {"text":"lalala"}. I try to ...
77
votes
3
answers
51k
views
Are a WSGI server and HTTP server required to serve a Flask app?
Setting up Flask with uWSGI and Nginx can be difficult. I tried following this DigitalOcean tutorial and still had trouble. Even with buildout scripts it takes time, and I need to write instructions ...
184
votes
8
answers
90k
views
Deploying a minimal flask app in docker - server connection issues
I have an app whose only dependency is flask, which runs fine outside docker and binds to the default port 5000. Here is the full source:
from flask import Flask
app = Flask(__name__)
app.debug = ...
272
votes
7
answers
177k
views
Passing HTML to template using Flask/Jinja2
I'm building an admin for Flask and SQLAlchemy, and I want to pass the HTML for the different inputs to my view using render_template. The templating framework seems to escape the HTML automatically, ...
130
votes
2
answers
211k
views
Link to Flask static files with url_for
How do you use url_for in Flask to reference a file in a folder? For example, I have some static files in the static folder, some of which may be in subfolders such as static/bootstrap.
When I try ...
21
votes
1
answer
15k
views
Store large data or a service connection per Flask session
I'm writing a small Flask application and am having it connect to Rserve using pyRserve. I want every session to initiate and then maintain its own Rserve connection.
Something like this:
session['...
230
votes
18
answers
331k
views
Flask raises TemplateNotFound error even though template file exists
I am trying to render the file home.html. The file exists in my project, but I keep getting jinja2.exceptions.TemplateNotFound: home.html when I try to render it. Why can't Flask find my template?
...
47
votes
2
answers
83k
views
How to pass a variable between Flask pages?
Suppose I have following case;
@app.route('/a', methods=['GET'])
def a():
a = numpy.ones([10,10])
...
return render_template(...) # this rendered page has a link to /b
@app.route('/b', methods=...
10
votes
3
answers
9k
views
JavaScript raises SyntaxError with data rendered in Jinja template
I am trying to pass data as JSON from a Flask route to a Jinja template rendering JavaScript. I want to iterate over the data using JavaScript. The browser shows SyntaxError: Unexpected token '&'...
44
votes
3
answers
50k
views
Flask view return error "View function did not return a response"
I have a view that calls a function to get the response. However, it gives the error View function did not return a response. How do I fix this?
from flask import Flask
app = Flask(__name__)
def ...
14
votes
1
answer
9k
views
Flask view raises TypeError: 'bool' object is not callable
I am trying to debug a view in my Flask app that is return a 500 status with the error TypeError: 'bool' object is not callable in the traceback. The view calls login_user from Flask-Login then ...
171
votes
7
answers
53k
views
Why does running the Flask dev server run itself twice?
I'm using Flask for developing a website and while in development I run flask using the following file:
#!/usr/bin/env python
from datetime import datetime
from app import app
import config
if ...
23
votes
1
answer
20k
views
Reference template variable within Jinja expression
I have a route defined like this:
@app.route('/magic/<filename>')
def moremagic(filename):
pass
And now in a template I want to call that route using url_for() like so:
<h1>you ...
219
votes
13
answers
445k
views
How to debug a Flask app
How are you meant to debug errors in Flask? Print to the console? Flash messages to the page? Or is there a more powerful option available to figure out what's happening when something goes wrong?
12
votes
1
answer
14k
views
Refering to a directory in a Flask app doesn't work unless the path is absolute
I downloaded nltk data into the data directory in my Flask app. The views reside in a blueprint in another directory on the same level as the data directory. In the view I'm trying to set the path to ...
27
votes
3
answers
29k
views
Display data streamed from a Flask view as it updates
I have a view that generates data and streams it in real time. I can't figure out how to send this data to a variable that I can use in my HTML template. My current solution just outputs the data to ...
139
votes
16
answers
152k
views
Add a prefix to all Flask routes
I have a prefix that I want to add to every route. Right now I add a constant to the route at every definition. Is there a way to do this automatically?
PREFIX = "/abc/123"
@app.route(PREFIX + "/")...
39
votes
2
answers
110k
views
Get a variable from the URL in a Flask route
I have a number of URLs that start with landingpage and end with a unique id. I need to be able to get the id from the URL, so that I can pass some data from another system to my Flask app. How can ...
110
votes
6
answers
324k
views
How to run a flask application?
I want to know the correct way to start a flask application. The docs show two different commands:
$ flask -a sample run
and
$ python3.4 sample.py
produce the same result and run the application ...
8
votes
2
answers
11k
views
Post values from an HTML form and access them in a Flask view
I have an HTML form that gets posted to a Flask route. However, request.form is empty. If I try to access one of the values by id, I get a 400 error. How do I post values from an HTML form and ...
158
votes
9
answers
260k
views
How can I pass data from Flask to JavaScript in a template?
My app makes a call to an API that returns a dictionary. I want to pass information from this dict to JavaScript in the view. I am using the Google Maps API in the JS, specifically, so I'd like to ...
612
votes
8
answers
779k
views
How can I get the named parameters from a URL using Flask?
When the user accesses this URL running on my flask app, I want the web service to be able to handle the parameters specified after the question mark:
http://10.1.1.1:5000/login?username=alex&...
335
votes
10
answers
419k
views
How to execute raw SQL in Flask-SQLAlchemy app
How do you execute raw SQL in SQLAlchemy?
I have a python web app that runs on flask and interfaces to the database through SQLAlchemy.
I need a way to run the raw SQL. The query involves multiple ...
223
votes
12
answers
352k
views
How to enable CORS in flask
I am trying to make a cross origin request using jquery but it keeps being reject with the message
XMLHttpRequest cannot load http://... No 'Access-Control-Allow-Origin'
header is present on the ...
635
votes
13
answers
561k
views
How do you access the query string in Flask routes?
How do you access query parameters or the query string in Flask routes? It's not obvious from the Flask documentation.
The example route /data below illustrates the context that I would like to access ...
328
votes
12
answers
301k
views
Get IP address of visitors using Flask for Python
I'm making a website where users can log on and download files, using the Flask micro-framework (based on Werkzeug) which uses Python (2.6 in my case).
I need to get the IP address of users when they ...
266
votes
6
answers
514k
views
Create dynamic URLs in Flask with url_for()
Half of my Flask routes requires a variable say, /<variable>/add or /<variable>/remove. How do I create links to those locations?
url_for() takes one argument for the function to route to ...
56
votes
2
answers
15k
views
Is it possible to use AngularJS with the Jinja2 template engine?
I have a Flask site and I want to use the AngularJS JavaScript framework. Unfortunately, it seems as if the delimiters overlap.
How do I use Angular with Jinja2 if both rely on double curly braces ...
101
votes
1
answer
82k
views
Testing code that requires a Flask app or request context
I am getting working outside of request context when trying to access session in a test. How can I set up a context when I'm testing something that requires one?
import unittest
from flask import ...
341
votes
5
answers
418k
views
json.dumps vs flask.jsonify
I am not sure I understand the purpose of the flask.jsonify method. I try to make a JSON string from this:
data = {"id": str(album.id), "title": album.title}
but what I get with json.dumps differs ...
162
votes
8
answers
198k
views
Read file data without saving it in Flask
I am writing my first flask application. I am dealing with file uploads, and basically what I want is to read the data/content of the uploaded file without saving it and then print it on the resulting ...
142
votes
15
answers
194k
views
jsonify a SQLAlchemy result set in Flask [duplicate]
I'm trying to jsonify a SQLAlchemy result set in Flask/Python.
The Flask mailing list suggested the following method http://librelist.com/browser//flask/2011/2/16/jsonify-sqlalchemy-pagination-...
354
votes
11
answers
701k
views
Redirecting to URL in Flask
I'm trying to do the equivalent of Response.redirect as in C# - i.e.: redirect to a specific URL - how do I go about this?
Here is my code:
import os
from flask import Flask
app = Flask(__name__)
@...
91
votes
1
answer
119k
views
What is the cause of the Bad Request Error when submitting form in Flask application?
After reading many similar sounding problems and the relevant Flask docs, I cannot seem to figure out what is generating the following error upon submitting a form:
400 Bad Request
The browser (or ...
78
votes
4
answers
84k
views
How to implement server push in Flask framework?
I am trying to build a small site with the server push functionality on Flask micro-web framework, but I did not know if there is a framework to work with directly.
I used Juggernaut, but it seems ...
23
votes
4
answers
23k
views
Flask application traceback doesn't show up in server log
I'm running my Flask application with uWSGI and nginx. There's a 500 error, but the traceback doesn't appear in the browser or the logs. How do I log the traceback from Flask?
uwsgi --http-socket ...
252
votes
3
answers
265k
views
Can I serve multiple clients using just Flask app.run() as standalone?
I know I can link Flask with Apache or other web servers. But, I was thinking of running Flask as a standalone server serving multiple clients simultaneously.
Is this possible? Do I have to handle ...
199
votes
6
answers
374k
views
Flask at first run: Do not use the development server in a production environment
I installed the Flask plugin in PyCharm Community Edition and I just have this simple code in my flask app:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return '<...
173
votes
19
answers
211k
views
TypeError: ObjectId('') is not JSON serializable
My response back from MongoDB after querying an aggregated function on document using Python, It returns valid response and i can print it but can not return it.
Error:
TypeError: ObjectId('...
103
votes
3
answers
149k
views
How can I add a background thread to flask?
I'm busy writing a small game server to try out flask. The game exposes an API via REST to users. It's easy for users to perform actions and query data, however I'd like to service the "game ...
97
votes
4
answers
135k
views
Flask to return image stored in database
My images are stored in a MongoDB, and I'd like to return them to the client, here is how the code is like:
@app.route("/images/<int:pid>.jpg")
def getImage(pid):
# get image binary from ...
42
votes
1
answer
34k
views
Capture arbitrary path in Flask route
I have a simple Flask route that I want to capture a path to a file. If I use <path> in the rule, it works for /get_dir/one but not /get_dir/one/two. How can I capture an arbitrary path, so ...
235
votes
5
answers
223k
views
How do I get the different parts of a Flask request's url?
I want to detect if the request came from the localhost:5000 or foo.herokuapp.com host and what path was requested. How do I get this information about a Flask request?
170
votes
21
answers
268k
views
How to stop flask application without using ctrl-c
I want to implement a command which can stop flask application by using flask-script.
I have searched the solution for a while. Because the framework doesn't provide app.stop() API, I am curious about ...