FAQ Database Discussion Community


Flask: [405 error] with pagination and POST request

python,flask,pagination
I have a Flask app with a route that uses pagination and has to handle GET and POST requests. I defined two routes for my function as described here to get the pagination working. When I post a form on a page other than the first then I get a...

Efficient way of handling XHR request in Python Flask

python,flask
Currently I am using following way of views to determine if request is AJAX / XHR. Accordingly I am returning json data and rendering the template file in Flask. This working perfectly so for in my application. from flask import request, render_template, jsonify @cinemascope.route('/cinema') def cinema(): if request.is_xhr: cinema =...

WTForm does not entirely repopulate form data upon editing a model

python,flask,wtforms,peewee
Edit: Category field is now able to repopulate. Made a mistake in retrieving the data. App.py has been edited. I recently created an "edit post" form in which the user clicks on a link, and a few parameters are sent to a function. My function searches for the post...

Ajax GET request confusion

javascript,python,ajax,flask
I am extremely new to javascript/ajax/flask and am trying to get data from my flask server. I am rendering the client.html template and need to get data from the /data route. app = Flask(__name__) @app.route("/data", methods=["GET"]) def submit_handler(): return 10 #example value @app.route('/client') def page(): return render_template('client.html') if __name__ ==...

Get “insert_id” for one to one relationship in Flask, SqlAlchemy

flask,flask-sqlalchemy
I'm trying to insert a new row through sqlalchemy. The parent table (Milestone) has a child table called Funding. Both tables share a relationship through a column called milestone_id. It is a one to one relationship. I have looked it up, but I can't figure out how to reference the...

Flask bad interpreter

python,bash,flask,shebang
Following this tutorial: http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iv-database I've reached the part where I'm supposed to create my first db and migrate it's tables. Having db_create.py, in the root directory of my xyzTest app, with the following contents: #!flask/bin/python from migrate.versioning import api from config import SQLALCHEMY_DATABASE_URI from config import SQLALCHEMY_MIGRATE_REPO from app import...

how to avoid flask insert duplicate entries?

python,flask,gunicorn
I want to update my database using the code snipped provided below: @app.route('/update') def update(): os.system('python update.py') return redirect(url_for('home')) But when I use gunicorn -w 4 to run the app and click the url http://127.0.0.1:5000/update once, it will run python update.py twice. The same content be insert into the database...

Flask: “from app import app”?

python,web-applications,flask
I'm following this tutorial to make a basic Flask app: and I don't understand the line of code in app/view.py that says from app import app. In that line, what do both of the app refer to? Do they both refer to the same thing? Note: I know that there...

Jinja macro doesn't see value passed to render_template

python,flask,jinja2
On certain pages I want my form drop down to be in a specific order and in other pages in a default order. When passing in a specific order from my app, my macro in form.html doesn't seem to see it. dropdown is never used, the template always displays the...

Flask-Restful, oauth, and Salesforce

python,rest,flask,oauth-2.0,salesforce
I am building out a REST service using Flask-RESTful that will allow users to connect to their salesforce Environment and pull data. Is it possible to secure a restful API with oauth2?! I cannot seem to find any documentation this....

Python Flask calling functions using buttons

javascript,python,ajax,json,flask
I'm pretty new to Python/Flask and especially scripting languages so please bare with me. Once the button in my flask template is pressed I'd like it to call a python function defined in app.py that I made to be available to be called within the template by typing the following...

Creating 2 dimensional array in Python Flask application Jinja2 Template

python,arrays,multidimensional-array,flask,jinja2
Within my Flask index.html template I wish to create a 2 dimensional array within a for loop. The for loop works perfectly fine but trying to 'set' an array that's multidimensional is not working. For example, one of the many things I've tried is: {% set matrix = [[] for...

Automatically reload Python-Flask application hosted on PythonAnywhere.com

python,flask,reload,pythonanywhere
I need to reload my flask application hosted on pythonAnywhere everyday. Is it possible to automatically reload the application using the code i already have? The application is a simple days counter: import datetime from flask import Flask, render_template app = Flask(__name__) wsgi_app = app.wsgi_app currentDate = datetime.date.today() userInput =...

“Runtime Error: working outside of application context” when trying to instantiate WTForms object in Flask view

python,flask,wtforms,flask-wtforms
So i have a form defined like this: class NewDashForm(Form): tabname = StringField('tabname', validators=[DataRequired(),Length(1,16)]) title = StringField('title', validators=[DataRequired(),Length(1,128)]) And I am importing it in my views.py file, but when I try to instantiate it like this: form = NewDashForm() I get the "working outside of application context" error. The application...

flask-security login via username and not email

python,flask,flask-security
I wanted to have the field in User model that through it the user logs in as username instead of email I defined: app.config['SECURITY_USER_IDENTITY_ATTRIBUTES'] = 'username' But I'm still getting: user_datastore.add_role_to_user(name, 'mgmt') File "/Users/boazin/sentinal/sentinel-cloud/.env/lib/python2.7/site-packages/flask_security/datastore.py", line 105, in add_role_to_user user, role = self._prepare_role_modify_args(user, role) File "/Users/boazin/sentinal/sentinel-cloud/.env/lib/python2.7/site-packages/flask_security/datastore.py",...

PUT request not working, Flask-RESTful, SQLAlchemy

flask,sqlalchemy,flask-sqlalchemy,put,flask-restful
I believe the issue is with committing the changes to the database (3rd to last line: db.session.commit()). For example take a user: username="Foo", email="[email protected]". If in the PUT request body I put {"email":"[email protected]"}, printing 'user.email' after the assignment reveals that the value is in fact changed. Afterwards however, upon querying...

Python/Flask deployment without pip

python,deployment,flask,web-deployment
I've usually deployed my Flask applications with a fairly simple fabric script that put the source on the target machine, used pip to install any dependencies, then fired up uwsgi with all the necessary settings and off it went. However, I have a new issue that some new security settings...

Query SQL data in Flask to use for charting without using the app.route decorator [closed]

python,sql-server,d3.js,flask
I am trying to query a SQL server in Flask, so that I can plot the data using d3.js. The way I've seen some people doing it (e.g. here) seems to be like this Create a function that retrieves the data Use the @app.route(/get_data) decorator Use the URL in d3.js...

How to let a Reference Field accept multiple Document schemas in MongoEngine?

python,flask,mongoengine
Context: I am writing an API (using Flask and MongoEngine) with multiple account types, including perhaps buildings. I need the database to hold some temporary accounts until a particular building registers. This is how I've been referencing just one type of user: current_holder_of_stuff = ReferenceField(ActiveUser) I know GenericReferenceField is also...

Twilio Client Python not Working in IOS Browser

javascript,python,ios,flask,twilio
I have created a simple twilio client application to make phone calls from Web Browser to phones. I used a sample Flask app to generate a secure Capability Token and used twilio.min.js library to handle calls from my HTML. The functionality works fine in Computer Browsers ans Android Phone Browsers,...

SQLAlchemy extension isn't registered when running app with Gunicorn

nginx,flask,flask-sqlalchemy,gunicorn
I have an application that works in development, but when I try to run it with Gunicorn it gives an error that the "sqlalchemy extension was not registered". From what I've read it seems that I need to call app.app_context() somewhere, but I'm not sure where. How do I fix...

Jinja2 for loop in javascript on a list not working but accessing individual elements works

javascript,python,flask,jinja2
I am working on a flask + jinja2 website which involves plotting some stored markers on a map. Python code resultroute['checkpointlist'] = CheckPoint.query.filter_by(route_id=route.code) return render_template('routes/edit.html',route=resultroute) Javascript in edit.html function addExistingMarkers() { //Individual access to elements var name0 = '{{route.checkpointlist[0].name}}'; var lat0 = {{route.checkpointlist[0].latitude}}; var long0 = {{route.checkpointlist[0].longitude}}; var marker =...

Deploying flask app on gunicorn, module object has no attribute

python,flask,gunicorn
I am trying to deploy my Flask application to gunicorn and I am getting following error. AttributeError: 'module' object has no attribute 'MyTopics' When I run server simply the Flask server, everything works fine: python http_server/server.py But when I run it under gunicorn, then I am getting the AttributeError gunicorn...

Wrapping Functions in Python 3.4 missing required positional argument

python,python-3.x,flask,flask-login
I am trying to customize a login_required decorator from the Flask-Login package. I have read the source code and mimicked the syntax. Mine: def login_role_required(f, req_roles=['any']): @wraps(f) def decorated_view(*args, **kwargs): if current_app.login_manager._login_disabled: return f(*args, **kwargs) if not current_user.is_authenticated(): return current_app.login_manager.unauthorized() if req_roles == ['any']: return f(*args, **kwargs) user_roles = current_user.get_roles...

How to retrieve ORM object in scope while submitting a form in flask

python,flask,wtforms
I am developing a blog application in flask. In html file to display posts there is option for commenting. But I am not able to retrieve the ORM object 'post' corrresponding to comment form while submitting form. My index.html file: {% extends "base.html" %} {% block content %} <h1>Hi, {{...

Pass Flask variable into Javascript

javascript,flask
I'm have a Flask website with a OpenLayers (javascript) web map. I'm trying to lookup an address to lat and lon coordinates, and then have the map render itself at that location. So at it's most basic, I'm trying to pass the result of an Flask sql query into some...

Basic Flask Issue w/ Importing

python,flask
I'm following a Flask tutorial and am getting an import error. I have a file called run.py which contains: from app import app app.run(debug = True) When I run ./run.py, I get: Traceback (most recent call last): File "./run.py", line 2, in <module> from app import app File "/Users/myName/Desktop/SquashScraper/app/__init__.py", line...

Flask Odd Behavior w/ Folder Creation/File Uploading

python,flask,indico
I'll preface this by saying I'm very new to Flask (this being my first project) and I'm interested in hacking it together, rather than best practice. I currently have code that fails to create folders named by the user in the pictures directory. I've tried searching for some answers here...

How to use Bootstrap Javascript from Flask-Bootstrap

python,twitter-bootstrap,flask,jinja2
I am using Flask-Bootstrap. I add {% extends "bootstrap/base.html" %} to my template to format it using Bootstrap. How can I use the javascript buttons with bootstrap, since I don't have the js files in my static folder?...

Automatically convert JSON to Object on Flask Request

java,python,json,spring-mvc,flask
In Spring MVC + Jackson (Java), I can have this: My Object (Java) public class Project { private long id; private String self; private String key; private String name; //Getters and Setters } Spring MVC Controller ... @RequestMapping(value="/doSomething", method=RequestMethod.POST) public String doSomething(@RequestBody Project project) { System.out.println(project.getName()); return "myPage"; } ......

Create content snippet with Jinja filter

python,flask,beautifulsoup,jinja2
I want to create content snippets for my home page. An example post looks something like <p>Your favorite Harry Potter characters enter the Game of Thrones universe, and you'll never guess what happens!</p> <readmore/> <p>...they all die</p> On the home page I only want the things before <readmore/> to show...

Serving Static Files Through Flash and Nginx?

python,nginx,flask
I have some static files I've been serving through Flask. On a given request, I run some processing and authentication, and then serve the file. I've been doing that using Flask's send_from_directory, but it looks like that caches the file for a bit, which is no good for me. I...

Flask seems to launch 2 instances of python [duplicate]

python,flask
This question already has an answer here: Why does running the Flask dev server run itself twice? 1 answer I have several Flask applications, but they all seem to launch 2 instances of Python. I have no idea why. Edit: I have googled for Flask and multiple instances of...

Running Flask with pycharm

python,flask,pycharm
I'm trying to follow https://developers.openshift.com/en/python-flask.html, to set up a flask app on openshift. I've followed the directions and have got it working at the command line using git-bash on win7. /myflaskapp (master) $ python wsgi.py 127.0.0.1 - - [16/Jun/2015 13:46:10] "GET / HTTP/1.1" 200 12 127.0.0.1 - - [16/Jun/2015...

Revert back to previous flask session variables when going back a page

python,session,flask
On a Flask website of mine, I have a session variable called 'thisQuestion' which put simply increments by 1 each time a page is loaded. Basically, the page returns questions from a database and the user can state whether they get the question right or wrong. The session variable increases...

smarter sqlalchemy wtf dynamic filter in a flask app

python,flask,sqlalchemy,flask-wtforms
I have a form that filters a table, and i would like the form entry to build a sqlalchemy statement. Because I have the option "No Filter", i can't just have the form field go into the filter('form field here'). But there must be a better way than doing every...

Update many to many association table with derived field

python,flask,sqlalchemy,many-to-many,flask-sqlalchemy
I'm writing a RESTful API using Flask, Flask-SQLalchemy and Flask-Restful. I have models for Contact and Category, and a helper table for mapping a many-to-many relationship between them. contactgrouping = db.Table('CONTACT_GROUPING', db.Column('catid', db.Integer, db.ForeignKey('CATEGORY.catid')), db.Column('contactid', db.Integer, db.ForeignKey('CONTACT.contactid')), db.Column('clientid', db.Integer, db.ForeignKey('CLIENT.clientid')), ) class Contact(db.Model): __tablename__ = 'CONTACT' contactid = db.Column(db.Integer, primary_key=True)...

Python Logging : how to add a custom field to LogRecord, and register a global callback to sets it's value

python,flask
In a Flask application, I want to add a user_id field added to every error log record that gets produced, whenever a user_id exists in the flask.session. I came up with the solution below but it's hackish, since it doesn't allow for the format string to drive the formatting of...

How to make Flask communicate with Flask across two different machines?

python,flask
I have a Flask app on one machine, and a second machine where some queries are required to be run from. The second machine doesn't render any pages, it will just be doing things behind the scenes for the first app. If I create a Flask app on the second...

Flask-WTF File contents lost when form fails validation and user resubmits form [closed]

python,flask,flask-wtforms
I'm having an issue where the contents of an uploaded file, via a FileField, are lost when the user resubmits form. I'm guessing the easy answer is to force the user to re-upload the file however I was wondering if there might be a workaround that can avoid having the...

Flask app structure is giving me module headaches

python,import,flask
I'm a newcomer to Python and Flask so I may be completely off with my app's organization. Here's what the directory structure looks like: + venv + bin + include + lib + myapp - __init__.py + config - __init__.py - development.py - production.py + templates - layout.html (more html...

flask - Server can't start [on hold]

python,flask
I am using linux mint mate 17 (base on ubuntu 14.04), I installed flask by" sudo apt-get install python-pip sudo pip install Flask I have python2.7.3 as my default python. Then write the hello world program hello.py: from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello World!'...

Issues sending and receiving a GET request using Flask

python,flask,request
I'm having issues with correctly sending and receiving a variable with a GET request. I cannot find any information online either. From the HTML form below, you can see I'm sending the value of 'question' but I'm also receiving 'topic' from a radio button in the form (though the code...

Default login_required rather than adding decorator everywhere

python,flask,flask-httpauth
I'm using Flask-HTTPAuth to handle authentication in my app. I have a lot of views, and I don't want to add login_required to every one of them. How can I make login required by default? from flask.ext.httpauth import HTTPBasicAuth auth = HTTPBasicAuth() @auth.verify_password def verify_password(username, password): return username == '111'...

Flask - Getting JavaScript and Python to Communicate

javascript,python,json,flask
I'm building a rather simple CRM using the Flask Python framework. I have a database of companies that we are interested in contacting. The user first inputs how many companies they would like to contact. The user is then redirected to this page: Essentially for each row/company on this page,...

Any way to use jinja2 and flask form instead of ajax and jquery or both?

jquery,python,flask,jinja2
I am wondering if there is a better way to do this. Right now I have jquery parsing over and selecting the active div of each row and sending via ajax the flask route. I was wondering if there was a way to do the same thing via jinja2 with...

Openshift redirect to https using flask-base example

python,.htaccess,flask,openshift
I'm trying to run my flask based app on free gear on Openshift only on https. Following this - I have added the .htaccess file to the root of my repo but it seems to be ignored, as it is not redirecting. The article talks about a wsgi directory but...

Executing database query gives “TypeError: not all arguments converted during string formatting”

python,flask
I'm trying to query my database with MySQLdb, but when I send a query with parameters I get TypeError: not all arguments converted during string formatting. I think it has something to do with the %s in the query. How do I fix this error? Main.py: from flask import Flask,...

How to run flask socket.io on localhost (xampp)

python,flask,xampp,flask-socketio
The tutorials I have seen use the following code to run the server: if __name__ == '__main__': socketio.run(app) My __init__.py file is: from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from sqlalchemy.orm import sessionmaker from sqlalchemy import * from flask.ext.socketio import SocketIO, emit app = Flask(__name__) socketio = SocketIO(app) app.debug...

How to create an item list to use multiple times on a Jinja2 template page?

python,python-3.x,for-loop,flask,jinja2
I want to create an HTML option list and display it multiple times on the template page. I tried to iterate through the list passed on to the template but this seems only to work once on the page: {% for item in points %} <option value="{{ item }}">{{ item...

Flask - Wtforms file upload with sendgrid API

python,flask,sendgrid
I'm making a relatively simple form which has a file input field. I would obviously like to have the uploaded file attached to the e-mail which is being sent via the Sendgrid python api. The form successfully sends at this point but I get no file upload, this is what...

Is there a shorter/better way to validate request params?

python,validation,python-2.7,flask,werkzeug
I keep repeating blocks like this to validate request params. Is there a shorter/better way to implement this? count = request.args.get('count', DEFAULT_COUNT) if count: try: count = int(count) except ValueError: count = DEFAULT_COUNT ...

Python Flask shutdown event handler

python,multithreading,flask
I'm using Flask as a REST endpoint which adds an application request to a queue. The queue is then consumed by a second thread. server.py def get_application(): global app app.debug = True app.queue = client.Agent() app.queue.start() return app @app.route("/api/v1/test/", methods=["POST"]) def test(): if request.method == "POST": try: #add the request...

Structure Flask project so I can import my app in other files

python,flask
I built this app a few months ago on the flask server and it was working perfectly. I have uploaded all files into the right directories but I keep getting an Unhandled Exception saying there is No module named app. Here is my structure: /static/ (all static files) /templates/ (all...

Sqlite3 : Unable to Authenticate

python,sqlite3,flask
I'm creating an application in flask to learn python and sqlite3. What I'm facing problem is my login authentication is not checking database entries and allowing every user to log in. And user data is been stored in database at the time of User signUp so database and tables are...

Peewee KeyError: 'i'

python,flask,peewee
I am getting an odd error from Python's peewee module that I am not able to resolve, any ideas? I basically want to have 'batches' that contain multiple companies within them. I am making a batch instance for each batch and assigning all of the companies within it to that...

Send JSON to Flask using requests

python,flask
I am trying to send some JSON data to a Flask app using the requests library. I expect to get application/json back from the server. This works fine when I use Postman, but when I use requests I get application/html back instead. import requests server_ip = 'server_ip:port/events' headers = {'Content-Type':...

for loop inside a flask function -Internal server error

python,flask,jinja
Cant delete this question but had to remove this code because of some issues.So removing the content.

Where should I place the secret key in Flask?

python,flask
While reading exploreflask.com, I learned that it is best practice to use two different config files, one for development and one for production. I don't understand whether to place the secret key inside of the development or production config. The private nature of the instance folder makes it a great...

Flask jsonify boolean response cannot be decoded in unit tests

python,unit-testing,flask
I am performing tests on my Flask application and I am expecting a json response built with jsonify. I use the ast library to decode the response. But I am getting the following error: Traceback (most recent call last): File "test_index.py", line 177, in test_create_venue data = ast.literal_eval(rv.data) File "/Users/manuelgodoy/anaconda/lib/python2.7/ast.py",...

How to serve clojurescript over flask

python,flask,clojurescript
I have a small Flask app and I want to use some ClojureScript to enhance the user experience on the client-side. Now I have trouble serving clojurescript via flask, as the paths get mixed up. Flask asserts that static files like Javascript scripts lie in a directory static. I have...

How to create mongoengine filter query from fields listed as string rather DocumentFields

python,flask,mongoengine
I am trying to write a function which can take all filter query as string and later I want to parse it and create respective filter query used in mongoengine. I tried using Q() but all this is not working with string. Working: return Q(Id__istartswith=value) Not working: _query = 'Id__istartswith='...

Jinja2 filter for URL pattern generation in flask views

python,flask,jinja2
I am developing a small Flask application to present data about Cinema. Each cinema has two categories associated with itself Language - language of that cinema. E.g. English, French Genre - E.g. Action, Comedy, Suspense User Case - There is a Cinema named Inception which is in English language and...

Creating a form with a varying number of repeated subform in Flask/WTForms

python,flask,flask-wtforms
My model currently has three related objects (there are more, but only three are relevant to this problem). User, Network, and Email. What I want to be able to do is have a defined set of Networks, and to allow each User to have an Email address on each Network...

flask restful: passing parameters to GET request

python,rest,flask,flask-restful
I want to create a resource that supports GET request in following way: /bar?key1=val1&key2=val2 I tried this code, but it is not working app = Flask(__name__) api = Api(app) class BarAPI(Resource): def get(key1, key2): return jsonify(dict(data=[key1, key2])) api.add_resource(BarAPI, '/bar', endpoint='bar') Thanks!...

Are there any known negatives to using Requests in Flask to interface to Cloudant on Buemix?

python,flask,couchdb,bluemix,cloudant
I am writing an app in Python Flask that makes use of the Python HTTP library Request to interface with Cloudant on Bluemix. It is an easy interface that allows me to directly access the Bluemix VCAP information for Cloudant and of course the Cloudant API. However it does not...

How to create table and insert data using MySQL and Flask

python,mysql,flask
I am trying to insert data into a MySQL table. I'm able to connect to the database but when trying to insert data it is giving internal server error. from flask import Flask from flaskext.mysql import MySQL mysql = MySQL() app = Flask(__name__) app.config['MYSQL_DATABASE_USER'] = 'root' app.config['MYSQL_DATABASE_DB'] = 'test' app.config['MYSQL_DATABASE_HOST']...

scoped_session object has no attribute 'create_all'

python,flask,sqlalchemy,flask-sqlalchemy
I have the following code that sets up my database with Flask-SQLAlchemy. I'm getting an exception "AttributeError: scoped_session object has no attribute 'create_all'". Can someone please explain to me why I'm getting the error and how I can fix it? :) __init__.py: from flask import Flask app = Flask(__name__) from...

Custom choices in WTForms SelectField bsed on current date

python,flask,wtforms
I would like to create a custom SelectField that provides different choices in based on the current date. For example, if it is the 13th of the month, the choices will be the values 1 through 13. How do I do this? def register_extensions(app): security.init_app(app, datastore=ds, register_form=forms.ExtendedRegisterForm) class ExtendedRegisterForm(RegisterForm): pay_month...

How to implement Flask Application Dispatching by Path with WSGI?

python,path,flask,wsgi,dispatch
I would like to use a single domain as a Staging Environment for multiple flask applications that will eventually run on their own domains. Something like: example_staging.com/app1 example_staging.com/app2 example_staging.com/app3 where: example_staging.com/app1 acts same as app1.example_staging.com example_staging.com/app2 acts same as app2.example_staging.com example_staging.com/app3 acts same as app3.example_staging.com or: example_staging.com/app1 acts same as...

How to pass arguments to included html in Flask web application

python,flask
I am developing a blog application in python with flask. In the view function form is passed as argument to render_template which calls 'index.html'. form works in index.html as expected. But there is a {% include '' %} tag which places 'post.htm'. Now I want to use same form repeatedly...

Python, Flask: How to set response header for all responses

python,flask,http-headers
I want to set all of my http headers responses to something like this: response.headers["X-Frame-Options"] = "SAMEORIGIN" I checked this question, but it only changes the header for one specific controller. I want to change all of my headers maybe in "before_request" function similar to the following logic. How can...

Correct way to protect flask-sentinel oauth management

python,flask
flask-sentinel creates a route to a management UI using app.add_url_rule. Wanting to apply some access control rules I wrapped it like this: from flask.ext import sentinel def requires_auth(fn): @wraps(fn) def decorated(*args, **kwargs): roles = [] if 'user' in session and 'roles' in session['user']: roles = session['user']['roles'] if 'admin' not in...

If ajax post success redirect user to new flask route

jquery,ajax,flask
I'm trying to have my user redirect after submitting but I keep getting ajax failed. $.ajax({ url: '/testing', contentType: 'application/json', type: 'post', dataType : 'json', data: JSON.stringify(data), success: function (data) { console.log(data); // ajax success callback }, error: function (response) { alert('ajax failed'); // ajax error callback }, }); });...

Flask server to notify webclient when changes occur

python,events,flask
I am building a server using Flask that will be called by a web client. When a certain change occurs on the db my Flask app interacts with, I need the web client to be alerted so it can display the update. Would someone be able to give me some...

What is the correct way to solve this circular import error with a Flask blueprint?

python,flask
I had a problem with a circular import, so I moved my blueprint import below my app definition. However, I'm still having an import error. Traceback (most recent call last): File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 2217, in <module> globals = debugger.run(setup['file'], None, None) File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 1643, in run pydev_imports.execfile(file,...

Flask does not load CSS file..?

python,html,css,python-2.7,flask
So the problem I'm having is that my web app only sometimes loads the css file and it uses the same css file data that was loaded even if I make edits to the css file and even when I delete the file. I have no clue what's going on....

Ajax post returning undefined

javascript,jquery,ajax,flask
I am trying to send the value of what is in the div's on the post via ajax. Specifically I'm trying to send what is in the div slick-active, so in this example console.log(data.results); would show 4 and 6 Here is the html: <div class="slider single-item"> <div class="slick-slide"><h3>1</h3></div> <div class="slick-slide"><h3>2</h3></div>...

Flask-login current_user issues

python,flask,flask-login
I've managed to get flask-login working but when I try use, for example current_user.username in my templates the value is None I suspect this is to do with my User.get() function but cannot for the life of my understand what I need to do so I can access the current...

Flask custom “not found” code

python,flask
I want to change the default 404 code, when flask doesn't finds the route, to other code. How can I do that?

Dereference a ReferenceField in Mongoengine

mongodb,flask,mongoengine,objectid,dbref
I am trying to dereference a reference field on my Flask backend and return the complete object with that certain field dereferenced. The field I am trying to dereference is defined like this: vouches_received = db.ListField(db.ReferenceField('Vouch')) The way I am trying to dereference it is like this: unverified_vouches = []...

How to add comments feature to posts in a flask web application

python,web-applications,flask,sqlalchemy,flask-wtforms
I am developing a web application with Flask.I am confused how to add comment feature to posts in a web application. Parts of my database models are a give below class Post(db.Model): id = db.Column(db.Integer, primary_key = True) title = db.Column(db.String(140)) body = db.Column(db.String(2000)) timestamp = db.Column(db.DateTime) user_id = db.Column(db.Integer,...

How do I set up a virtual environment with Flask using conda?

python,flask,virtualization,anaconda,conda
I wish to set up a virtual environment that I can use to develop web applications using the Flask framework for Python (3.4.2, Mac OS). I was given the instructions on how to do that here, using the virtualenv. However, trying to follow these instructions I ran into a problem:...

Flask-restful, marshal_with + nested data

python,flask,flask-restful
I have been stuck on this for a while now. My problem is I need to be able to use marshal_with and validate on nested fields coming from a POST. My test looks like this: def test_user_can_apply_with_multiple_dogs(self): data = { # User data 'registration_type': "guest", 'first_name': 'Alex', 'last_name': 'Daro', 'phone_number':...

Python Flask App building social network

python,flask
I am currently learning Python and trying to create a social network. I am not able to view other streams of people who have made posts on the wall. I get the following error AttributeError: 'User' object has no attribute 'models'. app.py @app.route('/stream') @app.route('/stream/<username>') def stream(username=None): template = 'stream.html' if...

Chained Dropdown in flask, get data from sqlite database

javascript,python,sqlite,drop-down-menu,flask
I am trying to get a html select tag with different counties (getting from database), when the user have selected a county, I want another select tag to enable and show the cities in that county (I have the data in a sqlite database, where the county id is in...

Flask can't find templates, gives 500 error

python,flask
so I've started coding using Flask framework and found it pretty easy. I am following a tutorial on youtube and got an error. I installed python, pip, flask and set environment variables and everything. My structure looks like this: /first_project /template template.html home.html routes.py Here is my template html: <!DOCTYPE...

Does Flask automatically delete aborted large file upload?

python,file-upload,flask
My Flask application will allow the upload of large files (up to 100 Mb) to my server. I was wondering how Flask managed the chunked file if the client decides to stop the upload half way. I read the documentation about File Upload but wasn't able to find that mentioned....

Flask submit data outside of form input fields

python,forms,input,flask,args
I'm working with Flask, and I am trying to submit some data that is not in input fields, to be added to the database. jinja code with the form(s) looks like this: {% for item in items %} <tr> <form id="adauga_{{ item.stoc_id }}" action="{{ url_for('adauga') }}" method="POST"> <td>{{ item.stoc_id }}</td>...

Flask Application returning ImportError: No module named user_auth.views

python-2.7,flask,importerror
I'm in the beginning stages of a Flask application. The problems I'm having is that whenever I attempt to run the application I get: app/application/___init___.py, line 11 in <module> from user_auth.views import auth ImportError: No module named user_auth.views I have no idea what the problem is. The import for the...

WTForms, how to attach JSON data to the request

ajax,flask,wtforms,flask-wtforms,wtforms-json
I'm bulding a form with WTForms for a Flask application. This form's las field is an address field that works with google PlacesAPI, so it autocompletes the address the user is introducing in that field. I want to be able to save all the data this PlacesAPI generates when the...

Flask - how to get query string parameters into the route parameters

flask,query-string,friendly-url
Im very much new to Flask, and one of the starting requirements is that i need SEO friendly urls. I have a route, say @app.route('/sales/') @app.route(/sales/<address>) def get_sales(addr): # do some magic here # render template of sales and a simple GET form that submits an address. <form action={{ url_for('get_sales')...

flask-assets - sass don't resolve relative path in @import scss directive

python,flask,sass,flask-assets
i have flask application with buildout environment ./bin/pip show flask | grep Version Version: 0.10.1 ./bin/pip show flask-assets | grep Version Version: 0.10 in src folder src/setup.py have following strings setup( name = 'spf', install_requires = [ 'flask', 'flask-assets', ], entry_points = { 'console_scripts': [ 'spf_dev = spf.manage:dev', /* see...

Jinja2 templates If condition not working correctly

python,flask,jinja2
I have an if-statement in a Jinja2 template in complete.html, but it doesn't run the right code regardless if the if-condition is True or False. I call a redirect url to another view function which then renders it, carrying the variable that determines the condition of the if-loop. I printed...

Syntax error python 2.7 [closed]

python,syntax,flask,pydub
Im have syntax error in def reverse app.route i know there is something wrong with getAudio but i dont know what. Here is example from pydub documentation sound1 = AudioSegment.from_file("/path/to/sound.wav", format="wav") And heres part of my code, commented @app.route('/Path/<filename>') def getFilePath(filename): return os.path.join(os.path.dirname(__file__), 'files', filename) @app.route('/Audio/<filename>') def getAudio(filename): return AudioSegment.from_file(getFilePath(filename,...

what is the significance of “ #!flask/bin/python ” in flask? [duplicate]

python,flask
This question already has an answer here: Why do you need to put #!/bin/bash at the beginning of a script file? 8 answers why this line #!flask/bin/python is added on the top of this code? from flask import Flask app = Flask(__name__) @app.route('/') def index(): return "Hello, World!" if...

Flask REST API responding with a JSONArray

android,python,json,rest,flask
I have created a simple REST API using Flask for an Android application. I'm having trouble implementing the GET method. It is supposed to return all the records in the form of a JSONArray. The response would look something like his { "tasks": [{ "task" : "Do it", "timestamp": 1433510946152...

Python Flask persistent object between requests

python,rest,flask,raspberry-pi
I am creating a web interface for OMXPlayer on the Raspberry Pi. I'm trying to create a more REST like API for controlling the video while its playing. The issue I'm having is how to control the video while it is playing. Currently I can create a Player object which...

Only function definitions covered by unit testing python/flask backend

python,unit-testing,flask
I would like to start by saying that i am a beginner at both flask and unit testing in Python, so bare that in mind. I am writing some unit testing for a backend that I am building for an android app. I am trying to write tests for the...

Flask Project root directory on openshift

python,flask,openshift
I'm getting started with flask and I'm deploying my app to openshift. My apps code: def get_users(): f = open('./users.txt') .... when I run: $ rhc tail flaskpq I see: [Sun Jun 21 09:05:20 2015] [error] [client 127.2.78.1] f = open('./user.txt') [Sun Jun 21 09:05:20 2015] [error] [client 127.2.78.1] IOError:...