What I am trying to achieve is pretty simple.
I want to use Flask to create a web app that connects to a remote Server via API calls (specifically ParseServer).
I am using a third-party library to achieve this and everything works perfectly when I am running my code in a stand-alone script. But when I add my code into the Flask I suddenly can't authenticate with the Server
Or to be more precise I get an 'unauthorized' error when executing an API call.
It seems to me that in Flask, the registration method used by the APi library is not remembered.
I tried many things of putting the registration and initialization code in different places in Flask, nothing worked.
I asked a similar question in the Github of the Library with no help.
So I guess I have two questions that could help me solve this
1) Where should I put a registration method and import of the files from this library?
&
2) What can I do to identify the issue specifically, eg. to know precisely what's wrong?
Here's some code
The Flask code is here
#app.route('/parseinsert')
def run_parse_db_insert():
"""The method for testing implementation and design of the Parse Db
"""
pc = ParseCommunication()
print(pc.get_all_names_rating_table())
return 'done'
The ParseCommunication is my Class that deals with Parse. If I run ParseCommunication from that script, with the same code as above in the main part, everything works perfectly.
I run the Flask app with dev_appserver.py from Google App Engine.
My folder structure
/parseTest
/aplication
views.py
app.yaml
run.py
My run.py code
import os
import sys
sys.path.insert(1, os.path.join(os.path.abspath('.'), 'lib'))
sys.path.insert(1, os.path.join(os.path.abspath('.'), 'application'))
import aplication
Let me know what else I could provide to help out.
Thank you in Advance
EDIT:
A stack trace as requested.
It's mostly related to the library (from what I can say?)
ERROR 2016-09-28 06:45:50,271 app.py:1587] Exception on /parseinsert [GET]
Traceback (most recent call last):
File "/home/theshade/Devel/ParseBabynames/parseTest/lib/flask/app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "/home/theshade/Devel/ParseBabynames/parseTest/lib/flask/app.py", line 1641, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/theshade/Devel/ParseBabynames/parseTest/lib/flask/app.py", line 1544, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/theshade/Devel/ParseBabynames/parseTest/lib/flask/app.py", line 1639, in full_dispatch_request
rv = self.dispatch_request()
File "/home/theshade/Devel/ParseBabynames/parseTest/lib/flask/app.py", line 1625, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/theshade/Devel/ParseBabynames/parseTest/aplication/views.py", line 34, in run_parse_db_insert
name = pc.get_user('testuser1')
File "/home/theshade/Devel/ParseBabynames/parseTest/aplication/parseCommunication.py", line 260, in get_user
return User.Query.get(username=uname)
File "/home/theshade/Devel/ParseBabynames/parseTest/lib/parse_rest/query.py", line 58, in get
return self.filter(**kw).get()
File "/home/theshade/Devel/ParseBabynames/parseTest/lib/parse_rest/query.py", line 150, in get
results = self._fetch()
File "/home/theshade/Devel/ParseBabynames/parseTest/lib/parse_rest/query.py", line 117, in _fetch
return self._manager._fetch(**options)
File "/home/theshade/Devel/ParseBabynames/parseTest/lib/parse_rest/query.py", line 41, in _fetch
return [klass(**it) for it in klass.GET(uri, **kw).get('results')]
File "/home/theshade/Devel/ParseBabynames/parseTest/lib/parse_rest/connection.py", line 108, in GET
return cls.execute(uri, 'GET', **kw)
File "/home/theshade/Devel/ParseBabynames/parseTest/lib/parse_rest/connection.py", line 102, in execute
raise exc(e.read())
ResourceRequestLoginRequired: {"error":"unauthorized"}
Parse requires keys and env variables. Check this line:
API_ROOT = os.environ.get('PARSE_API_ROOT') or 'https://api.parse.com/1'
Your error is in line 102 at:
https://github.com/milesrichardson/ParsePy/blob/master/parse_rest/connection.py
Before you can parse, you need to register:
from parse_rest.connection import register
APPLICATION_ID = '...'
REST_API_KEY = '...'
MASTER_KEY = '...'
register(APPLICATION_ID, REST_API_KEY, master_key=MASTER_KEY)
Related
Im going through Flask based tutorial "Learn flask framework" by Matt Copperwaite and now am stuck in following error.
After adding Flask-Admin I started to build admin dashboard with it. I tried to add Fileadmin module to control static files:
from flask_admin.contrib.fileadmin import FileAdmin
And now I'm getting next error, after trying to access corresponding web-form:
[2021-12-15 14:14:32,563] ERROR in app: Exception on /admin/blogfileadmin/ [GET]
Traceback (most recent call last):
File "/home/demino/WebProjects/blog/blog/lib/python3.9/site-packages/flask/app.py", line 2073, in wsgi_app
response = self.full_dispatch_request()
File "/home/demino/WebProjects/blog/blog/lib/python3.9/site-packages/flask/app.py", line 1518, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/demino/WebProjects/blog/blog/lib/python3.9/site-packages/flask/app.py", line 1516, in full_dispatch_request
rv = self.dispatch_request()
File "/home/demino/WebProjects/blog/blog/lib/python3.9/site-packages/flask/app.py", line 1502, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "/home/demino/WebProjects/blog/blog/lib/python3.9/site-packages/flask_admin/base.py", line 69, in inner
return self._run_view(f, *args, **kwargs)
File "/home/demino/WebProjects/blog/blog/lib/python3.9/site-packages/flask_admin/base.py", line 368, in _run_view
return fn(self, *args, **kwargs)
File "/home/demino/WebProjects/blog/blog/lib/python3.9/site-packages/flask_admin/contrib/fileadmin/__init__.py", line 812, in index_view
delete_form = self.delete_form()
File "/home/demino/WebProjects/blog/blog/lib/python3.9/site-packages/flask_admin/contrib/fileadmin/__init__.py", line 495, in delete_form
delete_form_class = self.get_delete_form()
File "/home/demino/WebProjects/blog/blog/lib/python3.9/site-packages/flask_admin/contrib/fileadmin/__init__.py", line 425, in get_delete_form
class DeleteForm(self.form_base_class):
File "/home/demino/WebProjects/blog/blog/lib/python3.9/site-packages/flask_admin/contrib/fileadmin/__init__.py", line 426, in DeleteForm
path = fields.HiddenField(validators=[validators.Required()])
AttributeError: module 'wtforms.validators' has no attribute 'Required'
I already experienced a bunch of problems caused by book being published in 2015, but so far I managed to solve them quite fast. Now Im stuck and cant find information that could help.
Thanks in advance.
Edit1: Solved - manually changed validators.required() call to validators.DataRequired() in flask-admin -> fileadmin init.py . They distinguished them in v1.0.2 (https://wtforms.readthedocs.io/en/stable/changes/#version-1-0-2). Not sure though which exactly, Data- or Input- requirement is correct here. Will see.
Solved - manually changed validators.required() call to validators.DataRequired() in flask-admin -> fileadmin init.py . They distinguished them in v1.0.2 (https://wtforms.readthedocs.io/en/stable/changes/#version-1-0-2).
I have a small flask server I'm running mostly for experimenting and tools I'm developing for self use (on my home network). It is running on development mode on a raspberry pi machine. It is configured to launch on startup via rc.local:
sudo -H -u pi /home/pi/Server/start.sh &
and the start.sh file reads
#!/bin/bash
cd /home/pi/Server
source /home/pi/Server/venv/bin/activate
export FLASK_APP=/home/pi/Server/app.py
export FLASK_ENV=development
export FLASK_RUN_HOST=192.168.1.104
export FLASK_RUN_PORT=5001
flask run
At the first couples of days everything was running fine, but now I get the following error:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/flask/app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/lib/python3/dist-packages/flask/app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "/usr/lib/python3/dist-packages/flask/app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/lib/python3/dist-packages/flask/_compat.py", line 35, in reraise
raise value
File "/usr/lib/python3/dist-packages/flask/app.py", line 2291, in wsgi_app
ctx.push()
File "/usr/lib/python3/dist-packages/flask/ctx.py", line 377, in push
self.app, self.request
File "/usr/lib/python3/dist-packages/flask/sessions.py", line 343, in open_session
data = s.loads(val, max_age=max_age)
File "/usr/lib/python3/dist-packages/itsdangerous.py", line 643, in loads
.unsign(s, max_age, return_timestamp=True)
File "/usr/lib/python3/dist-packages/itsdangerous.py", line 466, in unsign
return value, self.timestamp_to_datetime(timestamp)
File "/usr/lib/python3/dist-packages/itsdangerous.py", line 404, in timestamp_to_datetime
return datetime.utcfromtimestamp(ts + EPOCH)
OverflowError: timestamp out of range for platform time_t
From what I see here This is an issue of browser cache. How can I tell flask to cope with this?
Looks like you're using sessions/cookies? Try looking into that, maybe the date isn't proper or invalid. Try clearing it session.clear() or use a shorter expiration date. I've also had issues after upgrading from python 2 to 3 that messed up the cookies, if you've done that, you need to clear your cache so python3 date/time cookies can be set.
This seems to be an error when time returned is 0 from this Adafruit CircuitPython NTP issue. A direct approach would be to patch some flask dependencies with a PR.
However this seems more to be an error with your cache age. Try reducing it to a short time
#app.after_request
def after_request(response):
response.headers["Cache-Control"] = "max-age=300" # in second
return response
I'm not sure if this is an issue with flask or an issue with matplotlib. I've been able to access images in html and javascript, but now I can't seem to do it in python.
I have a directory tree structure like the following
\---Neuroethics_Behavioral_Task # 'root' directory for my flask app. Contents are shown below
+---jspsych-6.0
| +---css
| ## cutting this directory off here, jspsych is just a framework I'm using, not relevant
+---static
| +---images
| +---plugins
| | \---template
| +---textdata
| \---trial_stimuli
+---templates
\---__pycache__
I've just been using a script called experiment.py that lives in the topmost directory of my flask app (so in the /Neuroethics_Behavioral_Task/ folder). It executes a function called "generate_stim_for_trials(trials)". Create_stimuli uses matplotlib to create a bunch of pngs, each representing stimuli, and it's supposed to save these images in the /static/images/ directory.
I'm omitting most of the code related to the stimulus creation for... "ownership/copyright" purposes. Also that code really shouldn't be relevant All that needs to be said is that I create a pandas dataframe and plot it in matplotlib.
def generate_stim_for_trials(trials):
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import json
import os
lst_of_jsons_for_stimuli = []
stim_metadata_path = "/static/textdata/stimulus_data.json"
for each in range(trials):
stimuli_in_static = "images/stimulus_img" + str(each) + ".png"
stimuli_path = url_for('static', filename=stimuli_in_static)
# started ommitting code here...
df = # df variable gets created
df.plot(kind='barh', legend = False, stacked=True, color=['#e26a6a', '#3CB371', '#A9A9A9'])
plt.axis('off')
plt.margins(x=0)
plt.margins(y=0)
plt.grid(b=None)
plt.savefig(stimuli_path, bbox_inches='tight', pad_inches=-1) # error
The error I get is ultimately: FileNotFoundError: [Errno 2] No such file or directory: '/static/images/stimulus_img0.png'. I have the full error message but it's pretty long (and if moderators don't think it's useful, feel free to remove it/tell me to remove it).
Traceback (most recent call last):
File "D:\miniconda3\lib\site-packages\flask\app.py", line 2463, in __call__
return self.wsgi_app(environ, start_response)
File "D:\miniconda3\lib\site-packages\flask\app.py", line 2449, in wsgi_app
response = self.handle_exception(e)
File "D:\miniconda3\lib\site-packages\flask\app.py", line 1866, in handle_exce
ption
reraise(exc_type, exc_value, tb)
File "D:\miniconda3\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "D:\miniconda3\lib\site-packages\flask\app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "D:\miniconda3\lib\site-packages\flask\app.py", line 1951, in full_dispat
ch_request
rv = self.handle_user_exception(e)
File "D:\miniconda3\lib\site-packages\flask\app.py", line 1820, in handle_user
_exception
reraise(exc_type, exc_value, tb)
File "D:\miniconda3\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "D:\miniconda3\lib\site-packages\flask\app.py", line 1949, in full_dispat
ch_request
rv = self.dispatch_request()
File "D:\miniconda3\lib\site-packages\flask\app.py", line 1935, in dispatch_re
quest
return self.view_functions[rule.endpoint](**req.view_args)
File "D:\Projects\CogNeW\Neuroethics_Behavioral_Task\experiment.py", line 21,
in exp_js_psych_app
generate_stim_for_trials(total_trials)
File "D:\Projects\CogNeW\Neuroethics_Behavioral_Task\experiment.py", line 93,
in generate_stim_for_trials
plt.savefig(stimuli_path, bbox_inches='tight', pad_inches=-1)
File "D:\miniconda3\lib\site-packages\matplotlib\pyplot.py", line 722, in save
fig
res = fig.savefig(*args, **kwargs)
File "D:\miniconda3\lib\site-packages\matplotlib\figure.py", line 2180, in sav
efig
self.canvas.print_figure(fname, **kwargs)
File "D:\miniconda3\lib\site-packages\matplotlib\backends\backend_qt5agg.py",
line 88, in print_figure
super().print_figure(*args, **kwargs)
File "D:\miniconda3\lib\site-packages\matplotlib\backend_bases.py", line 2082,
in print_figure
**kwargs)
File "D:\miniconda3\lib\site-packages\matplotlib\backends\backend_agg.py", lin
e 530, in print_png
cbook.open_file_cm(filename_or_obj, "wb") as fh:
File "D:\miniconda3\lib\contextlib.py", line 81, in __enter__
return next(self.gen)
File "D:\miniconda3\lib\site-packages\matplotlib\cbook\__init__.py", line 447,
in open_file_cm
fh, opened = to_filehandle(path_or_file, mode, True, encoding)
File "D:\miniconda3\lib\site-packages\matplotlib\cbook\__init__.py", line 432,
in to_filehandle
fh = open(fname, flag, encoding=encoding)
FileNotFoundError: [Errno 2] No such file or directory: '/static/images/stimulus
_img0.png'
Again, this python file experiment.py exists at the topmost level of the flask module, in the "neuroethics_behavioral_task" directory. So it should be able to understand the path, /static/images since the static folder is also at that same level. But it doesn't.
Furthermore, here I'm trying to create/save a new file called stimulus_img0.png. So indeed, this file shouldn't exist yet -- it's getting created.
I can't tell if this is a matplotlib or flask issue, and I"m not sure how to resolve it because I'm not sure where my python program is actually looking at this point.
Edit 1
Well the 'mystery' is solved.
You know how you're supposed to do flask run or python -m flask run from a directory above your flask app?
If I just make the line plt.savefig('stimuli_img0.png'), the image(s) get saved in the directory above my flask application, aka the directory from which I'm executing python -m flask run.
So now my question is... What actually controls where python scripts in Flask save to? Is this actually the default behavior? I haven't encountered this in the html or js files in this flask app.
This question already has an answer here:
Import Flask extension when it is created in an app factory [duplicate]
(1 answer)
Closed 4 years ago.
When following tutorials the #ask decorator works when it is in the same file as ask = Ask(app, "/someroute") and after app = Flask(name). If I wish to put the #ask decorators in a view file in its own folder, using Blueprints no matter what I try I get "name 'ask' is not defined" with the decorator
I should say I am new to flask, but have now got a base app working with things like flask-principal working with flask-login and flask-navigation able to display menu items only if permitted.
I have been following the many flask-ask tutorials and everything works (so far), but I would prefer to have the view code in a separate views.py in its own folder and use Blueprints. I using create_app(config_name) instead of app = Flask(name) as suggested in many flask tutorials. I wish to do this as I want to keep my main __init__.py as clean as possible.
My newness to flask prevents me from doing something like using the alexa-skills-kit-sdk-for-python in flask as suggested by some people on Gitter (as flask-ask doesn't seem to be maintained anymore) and I still don't understand flask enough to work out why the ask object is not available in a separate views.py
In all truth I am tempted just to have everything in app/__init__.py as this is only a hobby app, but I am trying to structure my flask apps as suggested by many blogs, i.e. if there is no obvious fix for this then I will resort to the way that works, but I can't help feeling this is something I have done wrong from a flask perspective not flask-ask.
It may be worth adding that I had some install problems (choking on PyYAML, so I downloaded the package and manually installed the requirements then run setup.py (just in case that had an impact on the issue)
#app/__init__.py
#Pytho 3
from flask_ask import Ask, statement, question, session
....
def create_app(config_name):
app = Flask(__name__, instance_relative_config=True)
app.config.from_object(app_config[config_name])
app.config.from_pyfile('config.py')
Bootstrap(app)
db.init_app(app)
nav.init_app(app)
toolbar.init_app(app)
login_manager.init_app(app)
login_manager.login_message = "You must be logged in to access this page."
login_manager.login_view = "auth.login"
principals = Principal(app)
ask = Ask(app, "/alexa")
ask.init_app(app) #have also done it without this as some of the tutorials don't mention it
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint)
from .home import home as home_blueprint
app.register_blueprint(home_blueprint)
from .alexa import alexa as alexa_blueprint
app.register_blueprint(alexa_blueprint,url_prefix='/alexa')
# This loads fine
#ask.launch
def start_skill():
welcome_message = 'Hello there, would you like the news?'
return question(welcome_message)
If I remove the #ask decorator code and put it as below....
#app/alexa/views.py
from flask_ask import Ask, statement, question, session
import json
import requests
import time
import unidecode
from . import alexa
#alexa.route('/')
def alexa_route():
return('alexa')
#this doesn't work
#ask.launch # this is on line 33 (as below error)
def start_skill():
welcome_message = 'Hello there, would you like the news?'
return question(welcome_message)
I get (I am using venv so the paths are to a virtual environment)
File "/Users/username/Documents/Personal/Pi/template/lib/python3.7/site-packages/flask/app.py", line 2309, in call
return self.wsgi_app(environ, start_response)
File "/Users/username/Documents/Personal/Pi/template/lib/python3.7/site-packages/flask/app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "/Users/username/Documents/Personal/Pi/template/lib/python3.7/site-packages/flask/app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/username/Documents/Personal/Pi/template/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/Users/username/Documents/Personal/Pi/template/lib/python3.7/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/Users/username/Documents/Personal/Pi/template/lib/python3.7/site-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/username/Documents/Personal/Pi/template/lib/python3.7/site-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/username/Documents/Personal/Pi/template/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/Users/username/Documents/Personal/Pi/template/lib/python3.7/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/username/Documents/Personal/Pi/template/lib/python3.7/site-packages/flask_debugtoolbar/init.py", line 125, in dispatch_request
return view_func(**req.view_args)
File "/Users/username/Documents/Personal/Pi/baseapp/app/alexa/views.py", line 33, in alexa_route
return(ask)
NameError: name 'ask' is not defined
When using flask's app-factory, you should create the module's object outside of create_app :
#my_app/__init__.py
from flask_ask import Ask, statement, question, session
...
ask = Ask()
def create_app(config_name):
app = Flask(...)
...
ask.init_app(app)
Then you can import the object whenever you need it :
#my_app/alexa/views.py
from my_app import ask
...
#ask.launch
def start_skill():
welcome_message = 'Hello there, would you like the news?'
return question(welcome_message)
Beware of naming your app "app" as this can be confusing. I took the freedom to change it to 'my_app' for more clarity.
I have the following very simple app:
from lib.flask import Flask
from lib.flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class TestResource(Resource):
def get(self):
return {"a":"b","c":"d"}
api.add_resource(TestResource, "/")
When I run this, I get the following Exception:
Traceback (most recent call last):
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 266, in Handle
result = handler(dict(self._environ), self._StartResponse)
File "/Users/me/dev/project/src/main.py", line 22, in do_in_request
app(*args, **kwargs)
File "/Users/me/dev/project/src/lib/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/me/dev/project/src/lib/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Users/me/dev/project/src/lib/flask_restful/__init__.py", line 249, in error_router
if self._has_fr_route():
File "/Users/me/dev/project/src/lib/flask_restful/__init__.py", line 230, in _has_fr_route
if self._should_use_fr_error_handler():
File "/Users/me/dev/project/src/lib/flask_restful/__init__.py", line 211, in _should_use_fr_error_handler
adapter = self.app.create_url_adapter(request)
File "/Users/me/dev/project/src/lib/flask/app.py", line 1601, in create_url_adapter
return self.url_map.bind_to_environ(request.environ,
File "/Users/me/dev/project/src/lib/werkzeug/local.py", line 338, in __getattr__
return getattr(self._get_current_object(), name)
File "/Users/me/dev/project/src/lib/werkzeug/local.py", line 297, in _get_current_object
return self.__local()
File "/Users/me/dev/project/src/lib/flask/globals.py", line 20, in _lookup_req_object
raise RuntimeError('working outside of request context')
RuntimeError: working outside of request context
So I tried to put my entire app into what I thought would be the request context. In the code above, both the Flask object and the Api object are being instantiated once, and can be called by the server multiple times. From the traceback, it looks like the instantiation should happen within a request context, so I wrapped it like this:
def do_in_request(*args, **kwargs):
from lib.flask import Flask
from lib.flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class TestResource(Resource):
def get(self):
return {"a":"b","c":"d"}
api.add_resource(TestResource, "/")
app(*args, **kwargs)
app = do_in_request
That still raises the same error. What's going on, what do they mean by 'request context', and how do I fix this?
I started from scratch using the App Engine Flask Skeleton and added flask-restful as a dependency in requirements.txt and then just added more or less the code you have above and it worked without an issue. I added the repository to my github here if you want to use it - you can see the changes I made to the skeleton in this commit.
I'm not sure why your example isn't working, but one thing I noticed that could be causing issues is that you're doing from lib.flask .... It seems your third-party packages live in lib and you haven't necessarily "lifted" lib into your sys.path. The skeleton includes a vendoring library that makes sure that this is handled properly. It might be a potential source of the problem.
Either way, I hope the forked skeleton can help you get up and running.