• Now all data be ready for publish, We had made our blog alive now. Haha.



  • These days CCP GFW blocked all the IPs from US and when I switch my IP in google Cloud, the disk data cannot be restore again. I have to restart my blog totally, Now the website is still building…



Flask hangs when sending a post request to itself- Stack Overflow

Python PingBook 1 months ago (10-23) 17 0

Question

I’m trying to send a post request to my Flask app from one of its own views, but it hangs until I kill the server. If I do the request in JavaScript, it works fine. Why doesn’t it work from the Python code?

from flask import Blueprint, render_template, abort, request, Response, session, url_for
from jinja2 import TemplateNotFound

from flask.ext.wtf import Form
from wtforms import BooleanField, TextField, PasswordField

import requests

login = Blueprint(‘login’, __name__, template_folder=’templates’)

class LoginForm(Form):
email = TextField(‘Email’)
password = PasswordField(‘Password’)

@login.route(‘/login’, methods=[‘GET’, ‘POST’])
def _login():

form = LoginForm(request.form, csrf_enabled=False)

if form.validate_on_submit():
return requests.post(request.url_root + ‘/api/login’, data={“test”: True})

return render_template(‘login.html’, form=form)

Answer

Prior to 1.0, Flask’s development server was single-threaded by default. In that mode, it can only handle one request at a time. Making a request blocks until it receives the response. Your Flask code makes a request in the one thread, and then waits. There are no other threads to handle this second request. So the request never completes, and the original request waits forever.

Enable threads in the dev server to avoid the deadlock and fix the immediate problem.

app.run(threaded=True)

However, making a full HTTP request to the app from within the app should never be necessary and indicates a deeper design issue. For example, observe that the internal request will not have access to the session on the client’s browser. Extract the common code and call it internally, rather than making a new request.

def common_login(data):

@app.route(“/login”)
def login():

common_login(data)

@app.route(“/api/login”)
def api_login():

common_login(data)




Copyright from PingBook Blog, If not specified, they are original. This site uses BY-NC-SAProtocol authenticated.
For reprinting, please indicate the link of the original text:Flask hangs when sending a post request to itself- Stack Overflow
LIKE (0)
[1725641479@qq.com]
SHARE (0)
PingBook
Author:
We create, We sharing! Tag every value data your sharing
Submit comments
Cancel comments
emoji picture bold strikethrough center italic check in

Hi,you need to provide your name and email adress!

  • Name (Required)
  • Email (Required)
  • Website