Flask Yield don't work on Chrome - python

The following view only generate output during the execution on Firefox.
On Chrome the request flush the entire response once, when the while ends, at the end.
What are making the it don't work on Chrome?
#processes.route('/read_buffer/<int:pid>')
def read_buffer(pid):
def generate():
sent = 0
while not settings.buffers[pid]['finished']:
for i, row in enumerate(settings.buffers[pid]['lines'][sent:]):
sent += 1
yield row
gevent.sleep(0.5)
return flask.Response(
response=generate(),
status=200,
mimetype="text/plain"
)
App config:
from flask_cors import CORS
from flask_socketio import SocketIO
app = flask.Flask(__name__)
app.config['DEBUG'] = False
app.register_blueprint(processes.processes, url_prefix='/processes')
CORS(app)
socketio = SocketIO(app, async_mode='gevent')
socketio.run(
app=app,
host=_config.get('server', 'host', fallback='0.0.0.0'),
port=_config.getint('server', 'port', fallback=5000),
use_reloader=False
)
I'm using the SocketIO because I'm using it in other places.

seems like a known bug in Chrome:
https://bugs.chromium.org/p/chromium/issues/detail?id=156023

Related

Python Code on my XAMPP Website won´t work

from flask import Flask, render_template, request
import random
import datetime
app = Flask(__name__)
# List to store the submitted URLs
urls = []
#app.route('/')
def index():
return render_template('index.html')
#app.route('/submit', methods=['POST'])
def submit():
url = request.form['url']
# Add the URL to the list and return a success message
urls.append(url)
return "URL submitted successfully!"
#app.route('/stream')
def stream():
# Select a random URL from the last 20 days
now = datetime.datetime.now()
twenty_days_ago = now - datetime.timedelta(days=20)
recent_urls = [url for url in urls if url.submission_time > twenty_days_ago]
current_song_url = random.choice(recent_urls)
return render_template('stream.html', url=current_song_url)
if __name__ == '__main__':
app.run(debug=True)
I want to use this Code for my XAMPP Website (Html/php mostly used) but it only shows the code. So I watched some tutorials with config stuff and all that but then there is an internal server error. What should I do?
I tried to config Apache (httpd.conf) and installed everything (Python, Flask etc.)

Flask:XMLHttpRequest at '...' from origin has been blocked by CORS policy No 'Access-Control-Allow-Origin' header is present on the requested resource

I am currently trying to get a small server running on my RaspberryPi and accessing it from my PC within the LAN.
I get the following error when accessing the Raspberry, where the index.html is displayed to me just fine. Apparently it seems there are problems with my "resetList" endpoint.
I also tried the solution Solve Cross Origin Resource Sharing with Flask but it did not work for me. Thank you in advance.
I have the following Python code:
gevent.monkey.patch_all()
from flask import Flask, render_template
from flask_socketio import SocketIO
import dbfunctions as db
import json
from flask_cors import CORS
app = Flask(__name__, template_folder='./build', static_folder='./build/static')
CORS(app)
socket_io = SocketIO(app)
#app.route('/', methods=['GET', 'POST', 'PUT'])
def index():
return render_template('index.html')
# receiving messages
#socket_io.on('resetList')
def reset_list():
database = r"data.db"
conn = db.create_connection(database)
with conn:
data = db.get_data_without_initial(conn)
fields = ["id", "name", "profit", "sum", "high", "maxProfit", "last_update"]
json_list = []
for i in range(len(data)):
item_to_add = {fields[j]: data[i][j] for j in range(len(fields))}
json_list.append(item_to_add)
json.dumps(json_list)
socket_io.emit('receivedData', json_list)
if __name__ == '__main__':
socket_io.run(app, host='0.0.0.0', port=5000, debug=True)
i found a solution, the problem was not my python code it was my java code :/
a simple add of " transports: ["polling"] " solve the problem
import io from "socket.io-client";
let endPoint = "http://localhost:5000";
let socket = io.connect(`${endPoint}`, { transports: ["polling"] });
function receiveData(cb) {
socket.on("receivedData", (resp) => cb(resp));
}
export { receiveData };

Flask Socketio not updating data

I am working with Flask Socketio. My code right now console logs every time a user opens a page. However when I open the page in a new tab/window the console of the original user in not updated. Below is the code, have a look at it
let socket = io.connect("http://127.0.0.1:5000/")
socket.on("connect",() => {
socket.emit("my custom event",{text:"I have joined"})
})
socket.on("my response",function(msg) {
console.log(msg)
})
And here is the python code for flask
from flask import Flask, render_template, request
import requests
from flask_socketio import SocketIO, emit, send
app = Flask(__name__)
app.config["SECRET_KEY"] = "hope"
socketio = SocketIO(app)
#app.route('/')
def hello_world():
return render_template("index.html")
#app.route('/1')
def random_route():
return render_template("index2.html")
#socketio.on('message')
def message(data):
print(data)
#socketio.on('my custom event')
def handle_custom_event(data):
emit("my response", data)
if __name__ == "__main__":
socketio.run(app, debug=True)
The default for the emit function is to address the event only to the sender. If you want to address all your connected clients, you have to indicate so with the broadcast option:
#socketio.on('my custom event')
def handle_custom_event(data):
emit("my response", data, broadcast=True)

how get jwt token from IAP in Flask?

I have a simple Flask application on a Google App Engine, protected by Identity-Aware Proxy.
The authentication works well but I only recover the GCP_IAP_UID cookie, when I want to recover the JWT found in GCP_IAAP_AUTH_TOKEN_XXXXX.
I have tried
google.auht jwt
Flask request cookies
Requests
None of this module retrieve the token.
The browser shows the cookies I need (show image linked below), but Flask can't catch them.
Any idea is welcome
I try with the google.auth jwt, but it's empty
I try with Flask request.cookies but I get only on cookie, the UID (see code)
I try with requests.cookies.RequestsCookieJar (last try) but there is no cookie
My apps run with python 37 and here are the requirements:
Flask==1.1.2
Flask-SSLify==0.1.5
Werkzeug==1.0.1
google-api-python-client==1.6.0
google-cloud-storage==1.6.0
gunicorn==19.10.0
oauth2client==4.1.3
six==1.14.0
requests_toolbelt==0.9.1
google-auth-httplib2==0.0.3
ez-setup==0.9
Below the code of the init.py where I want to validate the jwt.
import logging
from flask import Flask, redirect, url_for, request
from google.auth import jwt
import requests
user_email = ""
nickname = ""
jwtr = ""
try:
import googleclouddebugger
googleclouddebugger.enable()
except ImportError:
pass
def create_app(config, debug=False, testing=True, config_overrides=None):
app = Flask(__name__)
app.config.from_object(config)
app.debug = debug
app.testing = testing
if config_overrides:
app.config.update(config_overrides)
# Configure logging
# if not app.testing:
logging.basicConfig(level=logging.INFO)
# Register the Bookshelf CRUD blueprint.
from .crud import crud
app.register_blueprint(crud, url_prefix='/app')
# Add a default root route.
#app.route("/")
def index():
jwtr = ""
# Goto see the log below
logging.info("1 nb cookies={}".format(len(request.cookies)))
logging.info("GCP_IAP_UID={}".format(request.cookies.get('GCP_IAP_UID')))
jar = requests.cookies.RequestsCookieJar()
logging.info("2 nb cookies={}".format(len(jar)))
for cle in jar.keys():
if cle.startswith('GCP_IAAP_AUTH_TOKEN_'):
jwtr = jar.get(cle)
logging.info("jwtr={}".format(jwtr))
try:
user_id, user_email, error_str = validate_iap_jwt_from_app_engine(jwtr,
'123456789012', 'xxxxx-yyyy')
if user_email is not None:
nickname = user_email.split('#')[0]
logging.info("nickmane="+nickname + " user_id="+user_id + " user_email=" +
user_email)
return redirect(url_for('crud.index'))
else:
return ""
except (ValueError, requests.exceptions.RequestException) as e:
logging.error("C'est moche !!{}!!".format(e))
return ""
Last but least a log file:
INFO:root:1 nb cookies=1
INFO:root:GCP_IAP_UID=10944565464656564
INFO:root:2 nb cookies=0
ERROR:root:**ERROR: JWT validation error Wrong number of segments in token: b''**
Cookies at browser level
in fact the jwt token can be found in the header like this:
AUTHORIZATION_HEADER = 'X-Goog-Iap-Jwt-Assertion'
if request.headers.get(AUTHORIZATION_HEADER):
jwtr = request.headers.get(AUTHORIZATION_HEADER)
logging.info("header authz={}".format(jwtr))
You can found all you need in https://cloud.google.com/iap/docs/signed-headers-howto

Flask - RuntimeError: No application found. Either work inside a view function or push an application context

I'm now trying to make an application that processes HTTP requests with REST APIs. The application uses Flask for the web framework, and it uses Celery for the asynchronous tasks.
Here's the application structure.
app.py
celery_app.py
controller/
controller.py
task/
task.py
(1) app.py
There are no lines for the Celery configuration.
from flask import Flask
...
app = Flask(__name__)
...
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
(2) celery.py
from consts.consts import Consts
from kombu.utils.url import quote
from celery import Celery
from config.config import Config
config = Config()
db_uri = 'db+' + config.get_db_uri()
aws_access_key = quote(config.get_config(Consts.AWS, Consts.AWS_ACCESS_KEY))
aws_secret_key = quote(config.get_config(Consts.AWS, Consts.AWS_SECRET_KEY))
broker_url = "sqs://{aws_access_key}:{aws_secret_key}#".format(
aws_access_key=aws_access_key, aws_secret_key=aws_secret_key
)
celery = Celery(
broker=broker_url,
backend=db_uri,
include=['task']
)
(3) task/task.py
I put all the tasks here.
from celery_app import celery
from flask import current_app as app
from model.model import db
#celery.task
def check_friend_status_from_db(user1, user2):
status = db.engine.execute(
"QUERY").fetchone()
return status
Now, the controller/controller.py file imports and calls the tasks as follows.
(4) controller/controller.py
from flask import Blueprint, request, json, render_template, jsonify
from mysql.connector import Error
from sqlalchemy import or_, and_
from consts.consts import StatusCode
from consts.consts import Consts
from model.model import db, FriendRequest
from outbound.request import Request
from util.logging import logger
from task.task import check_friend_status_from_db
controller_blueprint = Blueprint('controller_blueprint', __name__)
outbound_request = Request()
#controller_blueprint.route('/friend/status/<requested_from>/<requested_to>', methods=['GET'])
def check_friend_status(requested_from, requested_to):
logger.info('Checking the friend status')
try:
status = check_friend_status_from_db.apply_async((requested_from, requested_to)).get()
if status is None:
response = {
Consts.STATUS_CODE: StatusCode.OK,
Consts.FRIEND_STATUS: StatusCode.NO_RELATION
}
else:
response = {
Consts.STATUS_CODE: StatusCode.OK,
Consts.FRIEND_STATUS: status
}
except Error as e:
logger.error("TypeError:", e)
response = {
Consts.STATUS_CODE: StatusCode.ERROR
}
json_response = jsonify(response)
logger.info(json_response)
return json_response
When I run the code, I get the error as I mentioned on the title.
RuntimeError: No application found. Either work inside a view function or push an application context
and it turns out to be this part under the try block in the controller where the error is coming from.
status = check_friend_status_from_db.apply_async((requested_from, requested_to)).get()
Any solutions, please?
It looks like you need to register your blueprint controller_blueprint. Since this blueprint is not registered to your app, you are working outside the context of you application and hence the error.
You can do so in your app.py:
from controller.controller import controller_blueprint
app = Flask(__name__)
app.register_blueprint(controller_blueprint)

Categories

Resources