For educational purposes, we're building a very simple Flask app. While it runs smoothly locally, it no longer does when I copy the code to my virtual private server.
The route is defined as follows:
from flask import Flask, request, render_template
app = Flask(__name__)
#app.route("/", methods=["GET", "POST"])
def sign_up():
...
This is the function that uses autocomplete:
with connection.cursor() as cursor:
sql = f"SELECT * FROM movies WHERE title"
query = cursor.execute(sql)
data = cursor.fetchall()
# from flask import jsonify
results = [data[i]['title'] for i in range(len(data))]
return render_template("autocomplete.html", results=results)
autocomplete.html is located in the templates folder, which sits next to the Python program file.
And the web service is started like this:
if __name__ == '__main__':
app.run(host='0.0.0.0')
I can start the web service successfully, but when I connect using the URL, it returns a 500 error, and the server console shows:
[2020-05-28 16:19:47,099] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
File "/root/miniconda3/lib/python3.7/site-packages/flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "/root/miniconda3/lib/python3.7/site-packages/flask/app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/root/miniconda3/lib/python3.7/site-packages/flask/app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/root/miniconda3/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/root/miniconda3/lib/python3.7/site-packages/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "/root/miniconda3/lib/python3.7/site-packages/flask/app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "app.py", line 94, in sign_up
return render_template("autocomplete.html", results=results)
File "/root/miniconda3/lib/python3.7/site-packages/flask/templating.py", line 140, in render_template
ctx.app,
File "/root/miniconda3/lib/python3.7/site-packages/flask/templating.py", line 120, in _render
rv = template.render(context)
File "/root/miniconda3/lib/python3.7/site-packages/jinja2/environment.py", line 1090, in render
self.environment.handle_exception()
File "/root/miniconda3/lib/python3.7/site-packages/jinja2/environment.py", line 832, in handle_exception
reraise(*rewrite_traceback_stack(source=source))
File "/root/miniconda3/lib/python3.7/site-packages/jinja2/_compat.py", line 28, in reraise
raise value.with_traceback(tb)
File "/root/recommender/app-flask/templates/autocomplete.html", line 10, in top-level template code
$.getJSON("{{url_for('autocomplete')}}",{
File "/root/miniconda3/lib/python3.7/site-packages/flask/helpers.py", line 370, in url_for
return appctx.app.handle_url_build_error(error, endpoint, values)
File "/root/miniconda3/lib/python3.7/site-packages/flask/app.py", line 2216, in handle_url_build_error
reraise(exc_type, exc_value, tb)
File "/root/miniconda3/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/root/miniconda3/lib/python3.7/site-packages/flask/helpers.py", line 358, in url_for
endpoint, values, method=method, force_external=external
File "/root/miniconda3/lib/python3.7/site-packages/werkzeug/routing.py", line 2179, in build
raise BuildError(endpoint, values, method, self)
werkzeug.routing.BuildError: Could not build url for endpoint 'autocomplete'. Did you mean 'static' instead?
I assume this is because of a change in the URL, but I don't know how to solve this.
Can anyone help?
$.getJSON("{{url_for('autocomplete')}}",{
=> your code wrong at this line, read more about url_for in flask.
It's need to render route like: <blueprint_name>.<function_name> If use app as route use can skip blueprint_name => Ex: .sign_up
sample
Related
I am getting the error jinja2.exceptions.TemplateNotFound. Even I have my HTML files in the templates folder, still I am receiving this error. It was working fine sometime ago, and now I am getting this error.
Full error code:
Traceback (most recent call last)
File "E:\price\web\Lib\site-packages\flask\app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "E:\price\web\Lib\site-packages\flask\app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "E:\price\web\Lib\site-packages\flask\app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "E:\price\web\Lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "E:\price\web\Lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "E:\price\web\Lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "E:\price\web\Lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "E:\price\web\Lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "E:\price\web\Lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "E:\price\web\Lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "E:\price\web\flasktest.py", line 6, in index
return render_template('about.html')
File "E:\price\web\Lib\site-packages\flask\templating.py", line 138, in render_template
ctx.app.jinja_env.get_or_select_template(template_name_or_list),
File "E:\price\web\Lib\site-packages\jinja2\environment.py", line 1068, in get_or_select_template
return self.get_template(template_name_or_list, parent, globals)
File "E:\price\web\Lib\site-packages\jinja2\environment.py", line 997, in get_template
return self._load_template(name, globals)
File "E:\price\web\Lib\site-packages\jinja2\environment.py", line 958, in _load_template
template = self.loader.load(self, name, self.make_globals(globals))
File "E:\price\web\Lib\site-packages\jinja2\loaders.py", line 125, in load
source, filename, uptodate = self.get_source(environment, name)
File "E:\price\web\Lib\site-packages\flask\templating.py", line 60, in get_source
return self._get_source_fast(environment, template)
File "E:\price\web\Lib\site-packages\flask\templating.py", line 89, in _get_source_fast
raise TemplateNotFound(template)
jinja2.exceptions.TemplateNotFound: about.html
Here's my code snippet:
from flask import Flask, render_template
app = Flask('test', template_folder= 'templates')
#app.route('/')
def index():
return render_template('about.html')
if __name__ == '__main__':
app.run(debug = True, host = '127.0.0.1', port = 5000)
Here is the screenshot of my directories:
Update:
My code is working perfectly in a new file. Is it due to cache?
Tried app = Flask(name) but still same issue.
A new Test.py file works completely fine but not the old ones.
have a look at this topic https://flask.palletsprojects.com/en/2.0.x/api/#application-object and head over this section About the First Parameter
so my guess, you should import the right package name,
so try __name__ instead of test
app = Flask(__name__, template_folder='templates')
BTW, Flask already expects templates as default folder to look at, meaning it's optional and you can define your app like so
app = Flask(__name__)
Flask looks for templates by default in the "templates" folder https://flask.palletsprojects.com/en/2.0.x/quickstart/#rendering-templates.
Try this:
app = Flask(__name__)
#app.route('/')
def index():
return render_template('about.html')
Finally I got the solution where it went wrong.
I was doing this:
app = Flask('__name__')
But the correct way was this:
app = Flask(__name__)
I have a strange problem when using flask + TikTok API that I can't figure out.
I have the following code:
from flask import Flask
from flask_restful import Resource, Api
from TikTokApi import TikTokApi
tikTokApi = TikTokApi()
app = Flask(__name__)
api = Api(app)
#app.errorhandler(404)
def page_not_found(e):
return {'status': 'fail'}, 404
class TikTokProfile(Resource):
def get(self):
profileResponse = tikTokApi.getUserObject('rosiethepygmygoat')
return {'user' : profileResponse}
class TikTokMedia(Resource):
def get(self):
data = tikTokApi.getUserObject('rosiethepygmygoat')
response = tikTokApi.userPage(data["id"],data["secUid"])
return response
api.add_resource(TikTokProfile, '/profile')
api.add_resource(TikTokMedia, '/media')
if __name__ == '__main__':
app.run(debug=True)
When I visit /profile I get the user object, but when I try to get his user page via the /media route I get the following error:
INFO:werkzeug:127.0.0.1 - - [08/Jan/2021 09:20:45] "GET /media HTTP/1.1" 500 -
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_restful\__init__.py", line 272, in error_router
return original_handler(e)
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\_compat.py", line 38, in reraise
raise value.with_traceback(tb)
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_restful\__init__.py", line 272, in error_router
return original_handler(e)
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\_compat.py", line 38, in reraise
raise value.with_traceback(tb)
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_restful\__init__.py", line 468, in wrapper
resp = resource(*args, **kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\views.py", line 89, in view
return self.dispatch_request(*args, **kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_restful\__init__.py", line 583, in dispatch_request
resp = meth(*args, **kwargs)
File "D:\server\norway_group\tokmatic-sass\python\start.py", line 22, in get
response = tikTokApi.userPage(data["id"],data["secUid"])
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\TikTokApi\tiktok.py", line 562, in userPage
return self.getData(url=api_url, **kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\TikTokApi\tiktok.py", line 159, in getData
verify_fp, did, signature = self.browser.sign_url(**kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\TikTokApi\browser.py", line 164, in sign_url
page = self.create_page()
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\TikTokApi\browser.py", line 116, in create_page
context = self.browser.newContext(**iphone)
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\playwright\sync_api.py", line 6710, in newContext
self._sync(
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\playwright\_sync_base.py", line 95, in _sync
self._dispatcher_fiber.switch()
greenlet.error: cannot switch to a different thread
I thought that there is an issue with the TikTokApi package but when I try the same code outside the flask resource:
data = tikTokApi.getUserObject('rosiethepygmygoat')
response = tikTokApi.userPage(data["id"],data["secUid"])
print(response)
I get the object I need.
So am I missing a specific configuration for flask or something else? Any insights will be much appreciated.
Run your flask application using this comands:
flask run --without-threads
I need to render a string template that has tags that starts with a number and I get this exception:
jinja2.exceptions.TemplateSyntaxError: expected token 'end of print statement', got 'd_printer_name'
>>> jinja2.__version__
'2.10.3'
>>> flask.__version__
'1.1.1'
hello.py:
from flask import Flask, render_template_string
app = Flask(__name__)
#app.route("/")
def hello():
render_data = { "3d_printer_name": "A name for printer"}
rendered = render_template_string("Name: {{ 3d_printer_name}}.", **render_data)
return rendered
I also try putting {% autoescape false %} tag but the problem still is there.
Any help is welcome!
This is the traceback:
[2019-11-07 14:11:50,609] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
File "/site-packages/flask/app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "/site-packages/flask/app.py", line 1951, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/site-packages/flask/app.py", line 1820, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/site-packages/flask/app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "/site-packages/flask/app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/mgieco/Developments/tmp/flask_render/hello.py", line 8, in hello
decoration = render_template_string("Name: {{ 3d_printer_name}}.", **decoration_data)
File "/site-packages/flask/templating.py", line 155, in render_template_string
return _render(ctx.app.jinja_env.from_string(source), context, ctx.app)
File "/site-packages/jinja2/environment.py", line 880, in from_string
return cls.from_code(self, self.compile(source), globals, None)
File "/site-packages/jinja2/environment.py", line 591, in compile
self.handle_exception(exc_info, source_hint=source_hint)
File "/site-packages/jinja2/environment.py", line 780, in handle_exception
reraise(exc_type, exc_value, tb)
File "/site-packages/jinja2/_compat.py", line 37, in reraise
raise value.with_traceback(tb)
File "<unknown>", line 1, in template
File "/site-packages/jinja2/environment.py", line 497, in _parse
return Parser(self, source, name, encode_filename(filename)).parse()
File "/site-packages/jinja2/parser.py", line 901, in parse
result = nodes.Template(self.subparse(), lineno=1)
File "/site-packages/jinja2/parser.py", line 876, in subparse
self.stream.expect('variable_end')
File "/site-packages/jinja2/lexer.py", line 384, in expect
self.name, self.filename)
jinja2.exceptions.TemplateSyntaxError: expected token 'end of print statement', got 'd_printer_name'
127.0.0.1 - - [07/Nov/2019 14:11:50] "GET / HTTP/1.1" 500 -
Python can't use variables which start with number. And when you use **render_data then it convert dictionary to separated variables. It seems it skiped 3 and in error message it shows problem with d_printer_name
But you can send it as dictionary (instead of converting to separated variables)
render_template_string(..., my_data=render_data)
and then you can use it like dictionary
"{{ my_data['3d_printer_name'] }}"
from flask import Flask, render_template_string
app = Flask(__name__)
#app.route("/")
def hello():
render_data = {"3d_printer_name": "A name for printer"}
rendered = render_template_string("Name: {{ my_data['3d_printer_name'] }}.", my_data=render_data)
return rendered
app.run()
I'm trying to run https://github.com/swifthorseman/flask-peewee-heroku-setup locally on win 10, using python 3.6. I'm not sure if this project is designed to be run locally, maybe its only designed for heroku.
I have run the file teletubbies.py locally which created the db and table as you can see in the screenshot. To run it locally (or try to) I added the lines:
if __name__ == '__main__':
app.run(debug=True, use_reloader=True)
and I'm running it using
python server.py
The entire server.py file as I have it:
from flask import Flask, render_template, g
from tellytubbies import retrieve_all, db_proxy
app = Flask(__name__)
#app.before_request
def before_request():
g.db = db_proxy
g.db.connect()
#app.after_request
def after_request(response):
g.db.close()
return response
#app.route('/')
def index():
tellytubbies = retrieve_all()
return render_template("index.html", tellytubbies=tellytubbies)
if __name__ == '__main__':
app.run(debug=True, use_reloader=True)
By stepping through the code I don't see an error until the line:
tellytubbies = retrieve_all()
Which then crashes giving the following Traceback:
Traceback (most recent call last):
File "....myfile\lib\site-packages\flask\app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "....myfile\lib\site-packages\flask\app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "....myfile\lib\site-packages\flask\app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "....myfile\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "....myfile\lib\site-packages\flask\app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "....myfile\lib\site-packages\flask\app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "....myfile\lib\site-packages\flask\app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "....myfile\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "....myfile\lib\site-packages\flask\app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "....myfile\lib\site-packages\flask\app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "...\server.py", line 18, in index
tellytubbies = retrieve_all()
File "...\tellytubbies.py", line 32, in retrieve_all
for tellytubby in TellyTubby.select().order_by(TellyTubby.name):
File "....myfile\lib\site-packages\peewee.py", line 3281, in __iter__
return iter(self.execute())
File "....myfile\lib\site-packages\peewee.py", line 3274, in execute
self._qr = ResultWrapper(model_class, self._execute(), query_meta)
File "....myfile\lib\site-packages\peewee.py", line 2939, in _execute
return self.database.execute_sql(sql, params, self.require_commit)
File "....myfile\lib\site-packages\peewee.py", line 3837, in execute_sql
self.commit()
File "....myfile\lib\site-packages\peewee.py", line 3656, in __exit__
reraise(new_type, new_type(*exc_args), traceback)
File "....myfile\lib\site-packages\peewee.py", line 135, in reraise
raise value.with_traceback(tb)
File "....myfile\lib\site-packages\peewee.py", line 3830, in execute_sql
cursor.execute(sql, params or ())
peewee.OperationalError: no such table: tellytubby
The retrieve_all() function comes from the teletubbies.py file:
def retrieve_all():
results = []
for tellytubby in TellyTubby.select().order_by(TellyTubby.name):
results.append(tellytubby)
return results
the teletubbies.py does work when I run it as
python teletubbies.py
How can I get this working?
Your flask server works fine for me, after I run python teletubbies.py to initialize the sqlite database. However, if I remove the tellytubbies.db file that was created by running the script directly, the flask server fails with the same exception you quote.
Something to consider here is that when you run tellytubbies.py, the database file tellytubbies.db will be created in whatever directory you run it from. If you then run server.py from a different directory - for instance, if your IDE is running it - it won't find the other tellytubbies.db, so a new one will be created; but becase the tables were only created in your __main__ section in tellytubbies.py, the tables won't be created.
So your flask server needs to do some of the initialization that teletubbies.py is doing. I replaced the if __name__ == '__main__': section of your server.py with the following and it it works. It will work whether you keep the same database file or remove it between runs to start from scratch. I've added a check to make sure the same rows don't get inserted repeatedly.
if __name__ == '__main__':
from teletubbies import add_tellytubbies, TellyTubby
db_proxy.connect()
db_proxy.create_tables([TellyTubby], safe=True)
if TellyTubby.select().count() == 0:
add_tellytubbies()
app.run(debug=True, use_reloader=True)
I'm writing a function in Python Flask to deal with the oauth2 call backs of multiple api's.
The function as it stands is:
#app.route('/external_api/<api>/oauth2callback', methods=['POST', 'GET'])
def gdrive_oauth2callback(api):
toReturn = external_api.APIs[api]['lib'].oauth2callback(os.path.join(APP_OAUTH, str(api + '_id.json')))
userSession = UserSession()
userSession.addUserAuth(api)
return toReturn
However this causes a build error:
raise BuildError(endpoint, values, method)
BuildError: ('gdrive_oauth2callback', {}, None)
I'm confused as to why this is happening, as when i replace the api variable with the string 'gdrive' no error is created and it works perfectly. I'm calling the function in the same manner on both occasions (example.com/external_api/gdrive/oauth2callback), I'm wondering if Flask is unable to deal with both a POST request and a GET request at the same time, and if anyone else has had the same issue?
The full error log is below:
ERROR:app:Exception on /external_api/gdrive/connect [GET]
Traceback (most recent call last):
File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/app/app/views.py", line 43, in gdrive_connect
toReturn = external_api.APIs[api]['lib'].makeConnection()
File "/app/app/external_api/gdrive/api.py", line 14, in makeConnection
return flask.redirect(flask.url_for('gdrive_oauth2callback'))
File "/app/.heroku/python/lib/python2.7/site-packages/flask/helpers.py", line 312, in url_for
return appctx.app.handle_url_build_error(error, endpoint, values)
File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1641, in handle_url_build_error
reraise(exc_type, exc_value, tb)
File "/app/.heroku/python/lib/python2.7/site-packages/flask/helpers.py", line 305, in url_for
force_external=external)
File "/app/.heroku/python/lib/python2.7/site-packages/werkzeug/routing.py", line 1616, in build
raise BuildError(endpoint, values, method)
BuildError: ('gdrive_oauth2callback', {}, None) - at=info method=GET path
If anyone could give me any pointers on this that would be great! Thanks!
I think that flask must not be failing, if you take a look to this example, it works perfectly, http://flask.pocoo.org/snippets/62/.
I tried:
from flask import Flask
app = Flask(__name__)
#app.route("/<name>",methods=['POST', 'GET'])
def hello(name):
return "Hello World!"+name
if __name__ == "__main__":
app.run()
and it works fine on post and get requests. I know that isnt enougth but it shows what the problem probably isn’t.