I have been really stumped on this, been out of this game of web dev/python for a bit. I had a previously working Azure app service running this website, we did a minor HTML spelling change and re deployed. I am assuming some dependency got updated and now its broken. I don't know if this is a packaging version issue or if I have a missing import for my flask app.
I am getting a NameError: name 'Markup' is not defined error when trying to load a static html page. My app starts up just fine but I can't load the actual web pages.
Full Traceback
Traceback (most recent call last):
File "C:\Users\St**\PythonProjects\**Site-Portfolio\lib\site-packages\flask\app.py", line 2095, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\St**\PythonProjects\**Site-Portfolio\lib\site-packages\flask\app.py", line 2080, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\St**\PythonProjects\**Site-Portfolio\lib\site-packages\flask_cors\extension.py", line 165, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "C:\Users\St**\PythonProjects\**Site-Portfolio\lib\site-packages\flask\app.py", line 2077, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\St**\PythonProjects\**Site-Portfolio\lib\site-packages\flask\app.py", line 1525, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\St**\PythonProjects\**Site-Portfolio\lib\site-packages\flask_cors\extension.py", line 165, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "C:\Users\St**\PythonProjects\**Site-Portfolio\lib\site-packages\flask\app.py", line 1523, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\St**\PythonProjects\**Site-Portfolio\lib\site-packages\flask\app.py", line 1509, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "C:\Users\St**\PycharmProjects\**Site-portfolio\application.py", line 32, in index
return render_template("//index.html")
File "C:\Users\St**\PythonProjects\**Site-Portfolio\lib\site-packages\flask\templating.py", line 147, in render_template
ctx.app.update_template_context(context)
File "C:\Users\St**\PythonProjects\**Site-Portfolio\lib\site-packages\flask\app.py", line 756, in update_template_context
context.update(func())
File "C:\Users\St**\PythonProjects\**Site-Portfolio\lib\site-packages\flask_recaptcha.py", line 59, in get_code
return dict(recaptcha=Markup(self.get_code()))
NameError: name 'Markup' is not defined
127.0.0.1 - - [08/Apr/2022 17:02:51] "GET /?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 304 -
127.0.0.1 - - [08/Apr/2022 17:02:51] "GET /?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 304 -
127.0.0.1 - - [08/Apr/2022 17:02:51] "GET /?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 304 -
Process finished with exit code 0
Here is my code:
from flask import Flask, request, render_template, flash
from flask_mail import Mail, Message
from flask_cors import CORS, cross_origin
from flask_recaptcha import ReCaptcha
import requests
import json
import os
app = Flask(__name__, static_folder='static', static_url_path='')
recaptcha = ReCaptcha(app=app)
app.config['RECAPTCHA_ENABLED'] = True
app.config['RECAPTCHA_PUBLIC_KEY'] = '***********************'
app.config['RECAPTCHA_PRIVATE_KEY'] = '****************************'
#app.route('/', methods=['GET'])
def index():
return render_template("//index.html")
#app.route('/contact-us', methods=['GET'])
#app.route('/contact', methods=['GET', 'POST'])
def contact():
if request.method == 'POST':
r = requests.post('https://www.google.com/recaptcha/api/siteverify',
data={'secret': '***********',
'response': request.form['g-recaptcha-response']})
google_response = json.loads(r.text)
if google_response['success']:
contact_form = {'name': request.form['name'],
'email': request.form['email'],
'message': request.form['message']}
msg = Message(subject='Contact from website',
sender=contact_form['email'],
recipients=['*************'],
body=contact_form['message'])
mail.send(msg)
flash('Success, we will respond within at least 24 hours.')
return render_template('contact.html')
else:
flash('failed to submit, please retry or contact us at ************')
return render_template('contact.html')
return render_template('contact.html')
if __name__ == '__main__':
app.run()
My requirements.txt for package version
Flask>=1.0.2
jinja2>=2.11.3
Flask-Mail>=0.9.1
Flask-Cors>=3.0.9
Flask-Admin>=1.5.2
Flask-ReCaptcha>=0.4.2
Flask-SQLAlchemy>=2.3.2
Flask-WTF>=0.14.2
SQLAlchemy>=1.3.0
requests>=2.20.0
Flask-Login>=0.4.1
Werkzeug>=0.15.3
Flask-ReCaptcha is a very old project. The last update of Flask-ReCaptcha is on 2016. You'd better not use it.
Back to the error log itself, Flask-ReCaptcha has code like from jinja2 import Markup. But, since jinja2==3.1.0, Markup's position has changed. Try pip install jinja2==3.0.0`.
You will probably meet other problems as Flask-ReCaptcha is really old.
Go to Python installation folder
Go to Lib > site-packages
Open flask_recaptcha.py
You'll see something like this:
try:
from flask import request
from jinja2 import Markup
import requests
except ImportError as ex:
print("Missing dependencies")
Change it to:
try:
from flask import request
from markupsafe import Markup
import requests
except ImportError as ex:
print("Missing dependencies")
Related
Here is my script
"""
Concerto library
"""
import win32com.client
def concerto_authenticate(encrypted_request, expiry, mac):
"""
Authenticate request
"""
concerto_request = win32com.client.Dispatch(
"Concerto4xSecurity.ValidatedRequest")
secret_key = "XXX"
concerto_request.SetSecretKey(secret_key)
concerto_request.setEncryptedRequest(encrypted_request)
concerto_request.SetExpiry(expiry)
concerto_request.SetMAC(mac)
concerto_request.Validate()
return concerto_request
I call it from another page as so:
concerto_request = concerto.concerto_authenticate(encrypted_request, expiry, mac)
This works fine in my DEV environment. I am using Windows 2016 and IIS. It's using the inbuilt server that comes with Flask. Nothing fancy.
I moved all my files to PROD. Both DEV and PROD sit on the same server so have access to the exact same libraries. The only difference is that PROD uses Waitress.
No, when I run my code in PROD I get the following. This does not happen on the DEV URL, just the PROD one. The only difference being PROD uses Waitress and DEV does not.
Any suggestions?
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\flask\app.py", line 2077, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python310\lib\site-packages\flask\app.py", line 1525, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python310\lib\site-packages\flask\app.py", line 1523, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python310\lib\site-packages\flask\app.py", line 1509, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "E:\Apps\prod\digital\gp_clinicals\gp_clinicals.py", line 43, in gp_clinicals
concerto_request = concerto.concerto_authenticate(encrypted_request, expiry, mac)
File "E:\Apps\prod\digital\concerto.py", line 11, in concerto_authenticate
concerto_request = win32com.client.Dispatch(
File "C:\Python310\lib\site-packages\win32com\client\__init__.py", line 117, in Dispatch
dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch, userName, clsctx)
File "C:\Python310\lib\site-packages\win32com\client\dynamic.py", line 106, in _GetGoodDispatchAndUserName
return (_GetGoodDispatch(IDispatch, clsctx), userName)
File "C:\Python310\lib\site-packages\win32com\client\dynamic.py", line 88, in _GetGoodDispatch
IDispatch = pythoncom.CoCreateInstance(
pywintypes.com_error: (-2147221008, 'CoInitialize has not been called.', None, None)
2022-08-01 13:15:12,592 - ERROR - __init__.py - handle_error_500 - 88 - 500 Internal Server Error: The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
prod wsgi.py
"""
Application entry point
"""
from digital import init_app
from waitress import serve
app = init_app()
if __name__ == "__main__":
serve(app, host="internal.prod", url_scheme='https')
dev wsgi.py
"""
Application entry point
"""
from digital import init_app
app = init_app()
if __name__ == "__main__":
app.run(host="internal.dev",threaded=True)
I am using waitress on IIS with Flask.
I have a route that sets a session as follows
#gp_clinicals_bp.route("/setting", methods=["POST","GET"])
def gp_clinicals():
session["gp_clinicals_meds_repeat"] = "123456"
return session["gp_clinicals_meds_repeat"]
This returns, unsurprisingly:
123456
I have another route as follows:
#gp_clinicals_bp.route("/testing", methods=["POST","GET"])
def gp_clinicals_test():
return session["gp_clinicals_meds_repeat"]
Now, I get nothing back and the following in the error log
2022-08-02 20:03:51,126 - ERROR - app.py - log_exception - 1455 - Exception on /gp-clinicals/medication-repeat [GET]
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\flask\app.py", line 2077, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python310\lib\site-packages\flask\app.py", line 1525, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python310\lib\site-packages\flask\app.py", line 1523, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python310\lib\site-packages\flask\app.py", line 1509, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "E:\Apps\dev\digital\gp_clinicals\gp_clinicals.py", line 158, in gp_clinicals_medication_repeat
return str(session["gp_clinicals_meds_repeat"])
KeyError: 'gp_clinicals_meds_repeat'
2022-08-02 20:03:51,128 - ERROR - __init__.py - handle_error_500 - 92 - 500 Internal Server Error: The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
I'm the only one on the server. Below is a snippet from my initilisation file:
"""Initialize Flask app."""
import logging
import os
from logging.handlers import RotatingFileHandler
from flask import Flask, render_template, flash,request
from flask_session import Session
from flask_assets import Environment
from config import Config
if Config.FLASK_ENV == "development" and Config.DD_SERVICE:
patch_all()
sess = Session()
def init_app():
"""Create Flask application."""
app = Flask(__name__, instance_relative_config=False)
app.config["CACHE_TYPE"] = "null"
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.config["SESSION_TYPE"] = "filesystem"
app.config.from_object("config.Config")
assets = Environment()
assets.init_app(app)
sess.init_app(app)
What's going wrong? In the flask_session folder I am seeing files being created
Any advice? I tried using single apostophes instead of quotes but no go there either
The site in IIS is running through a reverse proxy in IIS - could that be doing it?
Hoping someone can help me address this issue.
I've got a very simple Flask server running in a docker container which accepts a new frame every time the /api/feed_image endpoint is called. The image passed through that endpoint then streams to the index.html from /video_feed.
The application works as expected initially, however, when I watch the resources being consumed using docker stats the memory usage slowly climbs until the entire system crashes.
Does anyone know what I could have missed or have any suggestions?
Thanks!
import os
import sys
from azure.iot.device.aio import IoTHubModuleClient
from flask import Response
from flask import request
from flask import Flask
from flask import render_template
import datetime
import time
import numpy as np
import cv2
import queue
frameQueue = queue.Queue()
app = Flask(__name__)
#app.route("/")
def index():
return render_template("index.html")
#app.route("/video_feed")
def video_feed():
print(len(frameQueue))
return Response(generate(), mimetype="multipart/x-mixed-replace; boundary=frame")
#app.route("/api/feed_image", methods=['POST'])
def read_image():
r = request
nparr = np.fromstring(r.data, np.uint8)
frameQueue.put(cv2.imdecode(nparr, cv2.IMREAD_COLOR))
def generate():
global frameQueue
while True:
outputFrame = frameQueue.get()
if outputFrame is None:
continue
(flag, encodedImage) = cv2.imencode(".jpg", outputFrame)
if not flag:
continue
yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + bytearray(encodedImage) + b'\r\n')
if __name__ == "__main__":
app.run(host='0.0.0.0', port='5001', debug=True, threaded=True, use_reloader=False)
After a long time I solved my own problem.
Turns out because I wasn't returning a Response object at the end of read_image(), Flask was generating an exception, which must have been caching in the background:
172.18.0.4 - - [22/Apr/2021 00:09:25] "POST /api/feed_image HTTP/1.1" 500 -
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1953, in full_dispatch_request
return self.finalize_request(rv)
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1968, in finalize_request
response = self.make_response(rv)
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2098, in make_response
"The view function did not return a valid response. The"
TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.
Adding a return statement solved the problem.
#app.route("/api/feed_image", methods=['POST'])
def read_image():
...
return Response(status=201)
Perhaps someone would have an explanation as to why this would happen?
Either way, I hope this helps someone!
I'm trying to build a blog as a portfolio sample using python3 and flask and flask_jwt_extended.
I can create a single file like this and it will run:
from flask_jwt_extended import (create_access_token, get_jwt_identity, JWTManager, jwt_required, get_raw_jwt)
from flask import Flask, request, Blueprint
app = Flask(__name__)
app.config['JWT_SECRET_KEY'] = 'this-is-super-secret'
app.config['JWT_BLACKLIST_ENABLED'] = True
app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access']
jwt = JWTManager(app)
#app.route(....)
#jwt required
But when I try to use Blueprint, it will not register the JWTManager
Here is my user.py file:
from flask_jwt_extended import (create_access_token, get_jwt_identity, JWTManager, jwt_required, get_raw_jwt)
from flask import Flask, request, Blueprint
app = Flask(__name__)
app.config['JWT_SECRET_KEY'] = 'this-is-super-secret'
app.config['JWT_BLACKLIST_ENABLED'] = True
app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access']
jwt = JWTManager(app)
user_blueprint = Blueprint('user_blueprint', __name__)
#user_blueprint.route(....)
#jwt required
here is my app.py:
from user import *
app = Flask(__name__)
app.register_blueprint(user_blueprint)
Now when I try to run app.py, this it returns a 500 (Internal Error) and will log this to the log file:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/flask_jwt_extended/utils.py", line 127, in _get_jwt_manager
return current_app.extensions['flask-jwt-extended']
KeyError: 'flask-jwt-extended'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python3.6/dist-packages/flask/_compat.py", line 35, in reraise
raise value
File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/ali/Desktop/cetia_api/user.py", line 63, in login
return create_token(user_inputs)
File "/home/ali/Desktop/cetia_api/user_functions.py", line 103, in create_token
access_token = create_access_token(identity=data, expires_delta=expires)
File "/usr/local/lib/python3.6/dist-packages/flask_jwt_extended/utils.py", line 156, in create_access_token
jwt_manager = _get_jwt_manager()
File "/usr/local/lib/python3.6/dist-packages/flask_jwt_extended/utils.py", line 129, in _get_jwt_manager
raise RuntimeError("You must initialize a JWTManager with this flask "
RuntimeError: You must initialize a JWTManager with this flask application before using this method
Could someone please tell me what to do? I tried EVERYTHING for the last 3 days. its been 20 hours of debugging and it's still not fixed
You need to use the same app in every location. Currently you are creating an app in your users.py file, and a different app in you app.py file.
Generally you will want to use the flask application factory pattern to do this (https://flask.palletsprojects.com/en/1.1.x/patterns/appfactories/). An example might look something like this:
extensions.py
from flask_jwt_extended import JWTManager
jwt = JWTManager()
users.py
from flask_jwt_extended import (create_access_token, get_jwt_identity, jwt_required, get_raw_jwt)
from flask import Flask, request, Blueprint
user_blueprint = Blueprint('user_blueprint', __name__)
#user_blueprint.route(....)
#jwt_required
app.py
from extensions import jwt
from users import users_blueprint
def create_app():
app = Flask(__name__)
app.secret_key = 'ChangeMe!'
app.config['JWT_BLACKLIST_ENABLED'] = True
app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access']
jwt.init_app(app)
app.register_blueprint(user_blueprint)
return app
main.py
from app import create_app
app = create_app()
if __name__ == '__main__':
app.run()
This question already has answers here:
Return JSON response from Flask view
(15 answers)
Closed 6 years ago.
Back again here with a flask question. I am a beginner and learn some awesome things from reddit (how to legit code).
Here is my code that I have grabbed certain information from an API that I am now trying to host locally through flask.
from flask import Flask, render_template
import httplib
import json
app = Flask(__name__)
#app.route('/')
def index():
connection = httplib.HTTPConnection('api.football-data.org')
headers = {'X-Auth-Token': 'this is my api token here', 'X-Response-Control': 'minified'}
connection.request('GET', '/v1/competitions/426/leagueTable', None, headers)
response = json.loads(connection.getresponse().read().decode())
return response
if __name__ == '__main__':
app.run()
When I run 127.0.0.1:5000 I get:
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
Here is what my server is telling me!
MacBooks-MBP:Football macbookpro13$ python Footy_Web.py
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
[2016-12-20 13:58:17,493] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/flask/app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "/Library/Python/2.7/site-packages/flask/app.py", line 1642, in full_dispatch_request
response = self.make_response(rv)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1746, in make_response
rv = self.response_class.force_type(rv, request.environ)
File "/Library/Python/2.7/site-packages/werkzeug/wrappers.py", line 847, in force_type
response = BaseResponse(*_run_wsgi_app(response, environ))
File "/Library/Python/2.7/site-packages/werkzeug/wrappers.py", line 57, in _run_wsgi_app
return _run_wsgi_app(*args)
File "/Library/Python/2.7/site-packages/werkzeug/test.py", line 871, in run_wsgi_app
app_rv = app(environ, start_response)
TypeError: 'dict' object is not callable
127.0.0.1 - - [20/Dec/2016 13:58:17] "GET / HTTP/1.1" 500 -
I should mention this code works outside of the flask framework!
You need to return a valid HTTP response. To do so, you can use jsonify like below:
return jsonify(response)
Do not forget to import jsonify like this:
from flask import jsonify
jsonify() returns a flask.Response() object.
You can also use json.dumps(), but in this case you need to add a http status code and a Content-Type header to return a valid HTTP response:
return json.dumps(response), 200, {'content-type': 'application/json'}