Mocking a HTTP server in Python - python

I'm writing a REST client and I need to mock a HTTP server in my tests. What would be the most appropriate library to do that? It would be great if I could create expected HTTP requests and compare them to actual.

Try HTTPretty, a HTTP client mock library for Python helps you focus on the client side.

You can also create a small mock server on your own.
I am using a small web server called Flask.
import flask
app = flask.Flask(__name__)
def callback():
return flask.jsonify(list())
app.add_url_rule("users", view_func=callback)
app.run()
This will spawn a server under http://localhost:5000/users executing the callback function.
I created a gist to provide a working example with shutdown mechanism etc.
https://gist.github.com/eruvanos/f6f62edb368a20aaa880e12976620db8

You can do this without using any external library by just running a temporary HTTP server.
For example mocking a https://api.ipify.org?format=json
"""Unit tests for ipify"""
import http.server
import threading
import unittest
import urllib.request
class MockIpifyHTTPRequestHandler(http.server.BaseHTTPRequestHandler):
"""HTTPServer mock request handler"""
def do_GET(self): # pylint: disable=invalid-name
"""Handle GET requests"""
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(b'{"ip":"1.2.3.45"}')
def log_request(self, code=None, size=None):
"""Don't log anything"""
class UnitTests(unittest.TestCase):
"""Unit tests for urlopen"""
def test_urlopen(self):
"""Test urlopen ipify"""
server = http.server.ThreadingHTTPServer(
("127.0.0.127", 9999), MockIpifyHTTPRequestHandler
)
with server:
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()
request = request = urllib.request.Request("http://127.0.0.127:9999/")
with urllib.request.urlopen(request) as response:
result = response.read()
server.shutdown()
self.assertEqual(result, b'{"ip":"1.2.3.45"}')
Alternative solution I found is in https://stackoverflow.com/a/34929900/15862

Mockintosh seems like another option.

Related

How to test python/flask app with third-party http lib?

I have a purest suite for my flask app that works great. However, I want to test some of my code that uses a third-party library (Qt) to send http requests. How is this possible? I see flask-testing has the live_server fixture which accomplishes this along with flask.url_for(), but it takes too much time to start up the server in the fixture.
Is there a faster way to send an http request from a third-party http lib to a flask app?
Thanks!
Turns out you can do this by manually converting the third-party request to the FlaskClient request, using a monkeypatch for whatever "send" method the third-party lib uses, then convert the flask.Response response back to a third-party reply object. All this occurs without using a TCP port.
Here is the fixture I wrote to bridge Qt http requests to the flask app:
#pytest.fixture
def qnam(qApp, client, monkeypatch):
def sendCustomRequest(request, verb, data):
# Qt -> Flask
headers = []
for name in request.rawHeaderList():
key = bytes(name).decode('utf-8')
value = bytes(request.rawHeader(name)).decode('utf-8')
headers.append((key, value))
query_string = None
if request.url().hasQuery():
query_string = request.url().query()
# method = request.attribute(QNetworkRequest.CustomVerbAttribute).decode('utf-8')
# send
response = FlaskClient.open(client,
request.url().path(),
method=verb.decode('utf-8'),
headers=headers,
data=data)
# Flask -> Qt
class NetworkReply(QNetworkReply):
def abort(self):
pass
reply = NetworkReply()
reply.setAttribute(QNetworkRequest.HttpStatusCodeAttribute, response.status_code)
for key, value in response.headers:
reply.setRawHeader(key.encode('utf-8'), value.encode('utf-8'))
reply.open(QIODevice.ReadWrite)
reply.write(response.data)
QTimer.singleShot(10, reply.finished.emit) # after return
return reply
qnam = QNetworkAccessManager.instance() # or wherever you get your instance
monkeypatch.setattr(qnam, 'sendCustomRequest', sendCustomRequest)
return ret

Calling a different endpoint from the same running web service in Tornado Python

I have two endpoints in the same web service and one should call the second one. But because the first one is not yet finished, the second one is not called. Below is the demonstration of what I need to achieve.
import tornado.ioloop
import tornado.web
import tornado.escape
import time
import requests
import itertools
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
class SampleApi1(tornado.web.RequestHandler):
def post(self):
print("1")
response = requests.post("http://localhost:5000/test2/")
self.write(response)
class SampleApi2(tornado.web.RequestHandler):
def post(self):
print("2")
self.write({"key": "value"})
def make_app():
return tornado.web.Application([(r"/test1/", SampleApi1),
(r"/test2/", SampleApi2)])
if __name__ == "__main__":
app = make_app()
app.listen(5000)
print("Listening on port 5000")
tornado.ioloop.IOLoop.current().start()
SampleApi1 calls SampleApi2 but SampleApi2 is not being called since SampleApi1 is not yet done. I've read gen.coroutines but it didn't work. I don't need to call SampleApi2 in parallel, I just need to call it from SampleApi1. Thank you in advance!
Tornado is an asynchronous framework, but the requests library is synchronous and blocking (see the tornado user's guide for more on these concepts). You shouldn't use requests in Tornado applications because it blocks the main thread. Instead, use Tornado's own AsyncHTTPClient (or another async http client like aiohttp):
async def post(self):
print("1")
client = tornado.httpclient.AsyncHTTPClient()
response = await client.fetch("http://localhost:5000/test2", method="POST", body=b"")
self.write(response)

Call a request in Python without waiting [duplicate]

I have some code that needs to execute after Flask returns a response. I don't think it's complex enough to set up a task queue like Celery for it. The key requirement is that Flask must return the response to the client before running this function. It can't wait for the function to execute.
There are some existing questions about this, but none of the answers seem to address running a task after the response is sent to the client, they still execute synchronously and then the response is returned.
Python Flask sending response immediately
Need to execute a function after returning the response in Flask
Flask end response and continue processing
The long story short is that Flask does not provide any special capabilities to accomplish this. For simple one-off tasks, consider Python's multithreading as shown below. For more complex configurations, use a task queue like RQ or Celery.
Why?
It's important to understand the functions Flask provides and why they do not accomplish the intended goal. All of these are useful in other cases and are good reading, but don't help with background tasks.
Flask's after_request handler
Flask's after_request handler, as detailed in this pattern for deferred request callbacks and this snippet on attaching different functions per request, will pass the request to the callback function. The intended use case is to modify the request, such as to attach a cookie.
Thus the request will wait around for these handlers to finish executing because the expectation is that the request itself will change as a result.
Flask's teardown_request handler
This is similar to after_request, but teardown_request doesn't receive the request object. So that means it won't wait for the request, right?
This seems like the solution, as this answer to a similar Stack Overflow question suggests. And since Flask's documentation explains that teardown callbacks are independent of the actual request and do not receive the request context, you'd have good reason to believe this.
Unfortunately, teardown_request is still synchronous, it just happens at a later part of Flask's request handling when the request is no longer modifiable. Flask will still wait for teardown functions to complete before returning the response, as this list of Flask callbacks and errors dictates.
Flask's streaming responses
Flask can stream responses by passing a generator to Response(), as this Stack Overflow answer to a similar question suggests.
With streaming, the client does begin receiving the response before the request concludes. However, the request still runs synchronously, so the worker handling the request is busy until the stream is finished.
This Flask pattern for streaming includes some documentation on using stream_with_context(), which is necessary to include the request context.
So what's the solution?
Flask doesn't offer a solution to run functions in the background because this isn't Flask's responsibility.
In most cases, the best way to solve this problem is to use a task queue such as RQ or Celery. These manage tricky things like configuration, scheduling, and distributing workers for you.This is the most common answer to this type of question because it is the most correct, and forces you to set things up in a way where you consider context, etc. correctly.
If you need to run a function in the background and don't want to set up a queue to manage this, you can use Python's built in threading or multiprocessing to spawn a background worker.
You can't access request or others of Flask's thread locals from background tasks, since the request will not be active there. Instead, pass the data you need from the view to the background thread when you create it.
#app.route('/start_task')
def start_task():
def do_work(value):
# do something that takes a long time
import time
time.sleep(value)
thread = Thread(target=do_work, kwargs={'value': request.args.get('value', 20)})
thread.start()
return 'started'
Flask is a WSGI app and as a result it fundamentally cannot handle anything after the response. This is why no such handler exists, the WSGI app itself is responsible only for constructing the response iterator object to the WSGI server.
A WSGI server however (like gunicorn) can very easily provide this functionality, but tying the application to the server is a very bad idea for a number of reasons.
For this exact reason, WSGI provides a spec for Middleware, and Werkzeug provides a number of helpers to simplify common Middleware functionality. Among them is a ClosingIterator class which allows you to hook methods up to the close method of the response iterator which is executed after the request is closed.
Here's an example of a naive after_response implementation done as a Flask extension:
import traceback
from werkzeug.wsgi import ClosingIterator
class AfterResponse:
def __init__(self, app=None):
self.callbacks = []
if app:
self.init_app(app)
def __call__(self, callback):
self.callbacks.append(callback)
return callback
def init_app(self, app):
# install extension
app.after_response = self
# install middleware
app.wsgi_app = AfterResponseMiddleware(app.wsgi_app, self)
def flush(self):
for fn in self.callbacks:
try:
fn()
except Exception:
traceback.print_exc()
class AfterResponseMiddleware:
def __init__(self, application, after_response_ext):
self.application = application
self.after_response_ext = after_response_ext
def __call__(self, environ, after_response):
iterator = self.application(environ, after_response)
try:
return ClosingIterator(iterator, [self.after_response_ext.flush])
except Exception:
traceback.print_exc()
return iterator
You can use this extension like this:
import flask
app = flask.Flask("after_response")
AfterResponse(app)
#app.after_response
def say_hi():
print("hi")
#app.route("/")
def home():
return "Success!\n"
When you curl "/" you'll see the following in your logs:
127.0.0.1 - - [24/Jun/2018 19:30:48] "GET / HTTP/1.1" 200 -
hi
This solves the issue simply without introducing either threads (GIL??) or having to install and manage a task queue and client software.
Flask now supports (via Werkzeug) a call_on_close callback decorator on response objects. Here is how you use it:
#app.after_request
def response_processor(response):
# Prepare all the local variables you need since the request context
# will be gone in the callback function
#response.call_on_close
def process_after_request():
# Do whatever is necessary here
pass
return response
Advantages:
call_on_close sets up functions for being called after the response is returned, using the WSGI spec for the close method.
No threads, no background jobs, no complicated setup. It runs in the same thread without blocking the request from returning.
Disadvantages:
No request context or app context. You have to save the variables you need, to pass into the closure.
No local stack as all that is being torn down. You have to make your own app context if you need it.
Flask-SQLAlchemy will fail silently if you're attempting to write to the database (I haven't figured out why, but likely due to the context shutting down). (It works, but if you have an existing object, it must be added to the new session using session.add or session.merge; not a disadvantage!)
There are 3 ways to do this, all work:
1. Thread
#app.route('/inner')
def foo():
for i in range(10):
sleep(1)
print(i)
return
#app.route('/inner', methods=['POST'])
def run_jobs():
try:
thread = Thread(target=foo)
thread.start()
return render_template("index_inner.html", img_path=DIR_OF_PHOTOS, video_path=UPLOAD_VIDEOS_FOLDER)
2. AfterResponse decorator
app = Flask(__name__)
AfterResponse(app)
#app.route('/inner', methods=['POST'])
def save_data():
pass
#app.after_response
def foo():
for i in range(10):
sleep(1)
print(i)
return
3. call_on_close
from time import sleep
from flask import Flask, Response, request
app = Flask('hello')
#app.route('/')
def hello():
response = Response('hello')
#response.call_on_close
def on_close():
for i in range(10):
sleep(1)
print(i)
return response
if __name__ == '__main__':
app.run()
Middleware Solution for Flask Blueprints
This is the same solution proposed by Matthew Story (which is the perfect solution IMHO - thanks Matthew), adapted for Flask Blueprints. The secret sauce here is to get hold of the app context using the current_app proxy. Read up here for more information (http://flask.pocoo.org/docs/1.0/appcontext/)
Let's assume the AfterThisResponse & AfterThisResponseMiddleware classes are placed in a module at .utils.after_this_response.py
Then where the Flask object creation occurs, you might have, eg...
__init__.py
from api.routes import my_blueprint
from .utils.after_this_response import AfterThisResponse
app = Flask( __name__ )
AfterThisResponse( app )
app.register_blueprint( my_blueprint.mod )
And then in your blueprint module...
a_blueprint.py
from flask import Blueprint, current_app
mod = Blueprint( 'a_blueprint', __name__, url_prefix=URL_PREFIX )
#mod.route( "/some_resource", methods=['GET', 'POST'] )
def some_resource():
# do some stuff here if you want
#current_app.after_this_response
def post_process():
# this will occur after you finish processing the route & return (below):
time.sleep(2)
print("after_response")
# do more stuff here if you like & then return like so:
return "Success!\n"
In addition to the other solutions, you can do route specific actions by combining after_this_request and response.call_on_close:
#app.route('/')
def index():
# Do your pre-response work here
msg = 'Hello World!'
#flask.after_this_request
def add_close_action(response):
#response.call_on_close
def process_after_request():
# Do your post-response work here
time.sleep(3.0)
print('Delayed: ' + msg)
return response
return msg
Thanks to Matthew Story and Paul Brackin, but I needed to change their proposals.
So the working solution is:
.
├── __init__.py
├── blueprint.py
└── library.py
# __init__.py
from flask import Flask
from .blueprint import bp
from .library import AfterResponse
app = Flask(__name__)
with app.app_context():
app.register_blueprint(bp, url_prefix='/')
AfterResponse(app)
# blueprint.py
from flask import Blueprint, request, current_app as app
from time import sleep
bp = Blueprint('app', __name__)
#bp.route('/')
def root():
body = request.json
#app.after_response
def worker():
print(body)
sleep(5)
print('finished_after_processing')
print('returned')
return 'finished_fast', 200
# library.py
from werkzeug.wsgi import ClosingIterator
from traceback import print_exc
class AfterResponse:
def __init__(self, application=None):
self.functions = list()
if application:
self.init_app(application)
def __call__(self, function):
self.functions.append(function)
def init_app(self, application):
application.after_response = self
application.wsgi_app = AfterResponseMiddleware(application.wsgi_app, self)
def flush(self):
while self.functions:
try:
self.functions.pop()()
except Exception:
print_exc()
class AfterResponseMiddleware:
def __init__(self, application, after_response_ext):
self.application = application
self.after_response_ext = after_response_ext
def __call__(self, environ, after_response):
iterator = self.application(environ, after_response)
try:
return ClosingIterator(iterator, [self.after_response_ext.flush])
except Exception:
print_exc()
return iterator
The source code can be found here
The signal request_finished receives a Response instance as parameter. Any after-processing can be done by connecting to that signal.
From https://flask-doc.readthedocs.io/en/latest/signals.html:
def log_response(sender, response, **extra):
sender.logger.debug('Request context is about to close down. '
'Response: %s', response)
from flask import request_finished
request_finished.connect(log_response, app)
Obs: In case of error, the signal got_request_exception can be used instead.
After read many topics.
I found the solution for me, if use Blueprint, it is worked for python 3.8 and SQLAlchemy
init.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
import dir
import time
from flask_mail import Mail
from flask_cors import CORS
import flask_excel as excel
# init SQLAlchemy so we can use it later in our models
dbb = SQLAlchemy()
def create_app():
app = Flask(__name__)
from .bp_route_1 import auth as bp_route_1_blueprint
app.register_blueprint(bp_route_1_blueprint)
CORS(app)
return app
bp_route_1.py
from flask import Blueprint, request, redirect, Response, url_for, abort, flash, render_template, \
copy_current_request_context
from . import dbb
from .models import #Import Models
from threading import Thread
bp_route_1 = Blueprint('bp_route_1', __name__)
#bp_route_1.route('/wehooks', methods=['POST'])
def route_1_wehooks_post():
#copy_current_request_context #to copy request
def foo_main():
# insert your code here
do_long_time_webhook(request)
Thread(target=foo_main).start()
print("do Webhook by Thread")
return Response(status=200)
def do_long_time_webhook(request):
try:
data = request.get_data()
print(data)
#do long tim function for webhook data
except Exception as e:
print('Dont do webhook', e)
To expand upon Kiran's response, I've added the call_on_close decorator to the copy_current_request_context decorator along with their imports.
I can confirm this works as expected.
from flask import Response, copy_current_request_context
#app.route('/example-route')
def response():
# Prepare response
#response.call_on_close
#copy_current_request_context
def post_processing():
# Process after response
pass
return response
You can use this code i have tried it.It works.
this code will print the string "message". after the 3 second ,from the scheduling time. You can change the time your self according to you requirement.
import time, traceback
import threading
def every(delay,message, task):
next_time = time.time() + delay
time.sleep(max(0, next_time - time.time()))
task(message)
def foo(message):
print(message+" :foo", time.time())
def main(message):
threading.Thread(target=lambda: every(3,message, foo)).start()
main("message")

Execute a function after Flask returns response

I have some code that needs to execute after Flask returns a response. I don't think it's complex enough to set up a task queue like Celery for it. The key requirement is that Flask must return the response to the client before running this function. It can't wait for the function to execute.
There are some existing questions about this, but none of the answers seem to address running a task after the response is sent to the client, they still execute synchronously and then the response is returned.
Python Flask sending response immediately
Need to execute a function after returning the response in Flask
Flask end response and continue processing
The long story short is that Flask does not provide any special capabilities to accomplish this. For simple one-off tasks, consider Python's multithreading as shown below. For more complex configurations, use a task queue like RQ or Celery.
Why?
It's important to understand the functions Flask provides and why they do not accomplish the intended goal. All of these are useful in other cases and are good reading, but don't help with background tasks.
Flask's after_request handler
Flask's after_request handler, as detailed in this pattern for deferred request callbacks and this snippet on attaching different functions per request, will pass the request to the callback function. The intended use case is to modify the request, such as to attach a cookie.
Thus the request will wait around for these handlers to finish executing because the expectation is that the request itself will change as a result.
Flask's teardown_request handler
This is similar to after_request, but teardown_request doesn't receive the request object. So that means it won't wait for the request, right?
This seems like the solution, as this answer to a similar Stack Overflow question suggests. And since Flask's documentation explains that teardown callbacks are independent of the actual request and do not receive the request context, you'd have good reason to believe this.
Unfortunately, teardown_request is still synchronous, it just happens at a later part of Flask's request handling when the request is no longer modifiable. Flask will still wait for teardown functions to complete before returning the response, as this list of Flask callbacks and errors dictates.
Flask's streaming responses
Flask can stream responses by passing a generator to Response(), as this Stack Overflow answer to a similar question suggests.
With streaming, the client does begin receiving the response before the request concludes. However, the request still runs synchronously, so the worker handling the request is busy until the stream is finished.
This Flask pattern for streaming includes some documentation on using stream_with_context(), which is necessary to include the request context.
So what's the solution?
Flask doesn't offer a solution to run functions in the background because this isn't Flask's responsibility.
In most cases, the best way to solve this problem is to use a task queue such as RQ or Celery. These manage tricky things like configuration, scheduling, and distributing workers for you.This is the most common answer to this type of question because it is the most correct, and forces you to set things up in a way where you consider context, etc. correctly.
If you need to run a function in the background and don't want to set up a queue to manage this, you can use Python's built in threading or multiprocessing to spawn a background worker.
You can't access request or others of Flask's thread locals from background tasks, since the request will not be active there. Instead, pass the data you need from the view to the background thread when you create it.
#app.route('/start_task')
def start_task():
def do_work(value):
# do something that takes a long time
import time
time.sleep(value)
thread = Thread(target=do_work, kwargs={'value': request.args.get('value', 20)})
thread.start()
return 'started'
Flask is a WSGI app and as a result it fundamentally cannot handle anything after the response. This is why no such handler exists, the WSGI app itself is responsible only for constructing the response iterator object to the WSGI server.
A WSGI server however (like gunicorn) can very easily provide this functionality, but tying the application to the server is a very bad idea for a number of reasons.
For this exact reason, WSGI provides a spec for Middleware, and Werkzeug provides a number of helpers to simplify common Middleware functionality. Among them is a ClosingIterator class which allows you to hook methods up to the close method of the response iterator which is executed after the request is closed.
Here's an example of a naive after_response implementation done as a Flask extension:
import traceback
from werkzeug.wsgi import ClosingIterator
class AfterResponse:
def __init__(self, app=None):
self.callbacks = []
if app:
self.init_app(app)
def __call__(self, callback):
self.callbacks.append(callback)
return callback
def init_app(self, app):
# install extension
app.after_response = self
# install middleware
app.wsgi_app = AfterResponseMiddleware(app.wsgi_app, self)
def flush(self):
for fn in self.callbacks:
try:
fn()
except Exception:
traceback.print_exc()
class AfterResponseMiddleware:
def __init__(self, application, after_response_ext):
self.application = application
self.after_response_ext = after_response_ext
def __call__(self, environ, after_response):
iterator = self.application(environ, after_response)
try:
return ClosingIterator(iterator, [self.after_response_ext.flush])
except Exception:
traceback.print_exc()
return iterator
You can use this extension like this:
import flask
app = flask.Flask("after_response")
AfterResponse(app)
#app.after_response
def say_hi():
print("hi")
#app.route("/")
def home():
return "Success!\n"
When you curl "/" you'll see the following in your logs:
127.0.0.1 - - [24/Jun/2018 19:30:48] "GET / HTTP/1.1" 200 -
hi
This solves the issue simply without introducing either threads (GIL??) or having to install and manage a task queue and client software.
Flask now supports (via Werkzeug) a call_on_close callback decorator on response objects. Here is how you use it:
#app.after_request
def response_processor(response):
# Prepare all the local variables you need since the request context
# will be gone in the callback function
#response.call_on_close
def process_after_request():
# Do whatever is necessary here
pass
return response
Advantages:
call_on_close sets up functions for being called after the response is returned, using the WSGI spec for the close method.
No threads, no background jobs, no complicated setup. It runs in the same thread without blocking the request from returning.
Disadvantages:
No request context or app context. You have to save the variables you need, to pass into the closure.
No local stack as all that is being torn down. You have to make your own app context if you need it.
Flask-SQLAlchemy will fail silently if you're attempting to write to the database (I haven't figured out why, but likely due to the context shutting down). (It works, but if you have an existing object, it must be added to the new session using session.add or session.merge; not a disadvantage!)
There are 3 ways to do this, all work:
1. Thread
#app.route('/inner')
def foo():
for i in range(10):
sleep(1)
print(i)
return
#app.route('/inner', methods=['POST'])
def run_jobs():
try:
thread = Thread(target=foo)
thread.start()
return render_template("index_inner.html", img_path=DIR_OF_PHOTOS, video_path=UPLOAD_VIDEOS_FOLDER)
2. AfterResponse decorator
app = Flask(__name__)
AfterResponse(app)
#app.route('/inner', methods=['POST'])
def save_data():
pass
#app.after_response
def foo():
for i in range(10):
sleep(1)
print(i)
return
3. call_on_close
from time import sleep
from flask import Flask, Response, request
app = Flask('hello')
#app.route('/')
def hello():
response = Response('hello')
#response.call_on_close
def on_close():
for i in range(10):
sleep(1)
print(i)
return response
if __name__ == '__main__':
app.run()
Middleware Solution for Flask Blueprints
This is the same solution proposed by Matthew Story (which is the perfect solution IMHO - thanks Matthew), adapted for Flask Blueprints. The secret sauce here is to get hold of the app context using the current_app proxy. Read up here for more information (http://flask.pocoo.org/docs/1.0/appcontext/)
Let's assume the AfterThisResponse & AfterThisResponseMiddleware classes are placed in a module at .utils.after_this_response.py
Then where the Flask object creation occurs, you might have, eg...
__init__.py
from api.routes import my_blueprint
from .utils.after_this_response import AfterThisResponse
app = Flask( __name__ )
AfterThisResponse( app )
app.register_blueprint( my_blueprint.mod )
And then in your blueprint module...
a_blueprint.py
from flask import Blueprint, current_app
mod = Blueprint( 'a_blueprint', __name__, url_prefix=URL_PREFIX )
#mod.route( "/some_resource", methods=['GET', 'POST'] )
def some_resource():
# do some stuff here if you want
#current_app.after_this_response
def post_process():
# this will occur after you finish processing the route & return (below):
time.sleep(2)
print("after_response")
# do more stuff here if you like & then return like so:
return "Success!\n"
In addition to the other solutions, you can do route specific actions by combining after_this_request and response.call_on_close:
#app.route('/')
def index():
# Do your pre-response work here
msg = 'Hello World!'
#flask.after_this_request
def add_close_action(response):
#response.call_on_close
def process_after_request():
# Do your post-response work here
time.sleep(3.0)
print('Delayed: ' + msg)
return response
return msg
Thanks to Matthew Story and Paul Brackin, but I needed to change their proposals.
So the working solution is:
.
├── __init__.py
├── blueprint.py
└── library.py
# __init__.py
from flask import Flask
from .blueprint import bp
from .library import AfterResponse
app = Flask(__name__)
with app.app_context():
app.register_blueprint(bp, url_prefix='/')
AfterResponse(app)
# blueprint.py
from flask import Blueprint, request, current_app as app
from time import sleep
bp = Blueprint('app', __name__)
#bp.route('/')
def root():
body = request.json
#app.after_response
def worker():
print(body)
sleep(5)
print('finished_after_processing')
print('returned')
return 'finished_fast', 200
# library.py
from werkzeug.wsgi import ClosingIterator
from traceback import print_exc
class AfterResponse:
def __init__(self, application=None):
self.functions = list()
if application:
self.init_app(application)
def __call__(self, function):
self.functions.append(function)
def init_app(self, application):
application.after_response = self
application.wsgi_app = AfterResponseMiddleware(application.wsgi_app, self)
def flush(self):
while self.functions:
try:
self.functions.pop()()
except Exception:
print_exc()
class AfterResponseMiddleware:
def __init__(self, application, after_response_ext):
self.application = application
self.after_response_ext = after_response_ext
def __call__(self, environ, after_response):
iterator = self.application(environ, after_response)
try:
return ClosingIterator(iterator, [self.after_response_ext.flush])
except Exception:
print_exc()
return iterator
The source code can be found here
The signal request_finished receives a Response instance as parameter. Any after-processing can be done by connecting to that signal.
From https://flask-doc.readthedocs.io/en/latest/signals.html:
def log_response(sender, response, **extra):
sender.logger.debug('Request context is about to close down. '
'Response: %s', response)
from flask import request_finished
request_finished.connect(log_response, app)
Obs: In case of error, the signal got_request_exception can be used instead.
After read many topics.
I found the solution for me, if use Blueprint, it is worked for python 3.8 and SQLAlchemy
init.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
import dir
import time
from flask_mail import Mail
from flask_cors import CORS
import flask_excel as excel
# init SQLAlchemy so we can use it later in our models
dbb = SQLAlchemy()
def create_app():
app = Flask(__name__)
from .bp_route_1 import auth as bp_route_1_blueprint
app.register_blueprint(bp_route_1_blueprint)
CORS(app)
return app
bp_route_1.py
from flask import Blueprint, request, redirect, Response, url_for, abort, flash, render_template, \
copy_current_request_context
from . import dbb
from .models import #Import Models
from threading import Thread
bp_route_1 = Blueprint('bp_route_1', __name__)
#bp_route_1.route('/wehooks', methods=['POST'])
def route_1_wehooks_post():
#copy_current_request_context #to copy request
def foo_main():
# insert your code here
do_long_time_webhook(request)
Thread(target=foo_main).start()
print("do Webhook by Thread")
return Response(status=200)
def do_long_time_webhook(request):
try:
data = request.get_data()
print(data)
#do long tim function for webhook data
except Exception as e:
print('Dont do webhook', e)
To expand upon Kiran's response, I've added the call_on_close decorator to the copy_current_request_context decorator along with their imports.
I can confirm this works as expected.
from flask import Response, copy_current_request_context
#app.route('/example-route')
def response():
# Prepare response
#response.call_on_close
#copy_current_request_context
def post_processing():
# Process after response
pass
return response
You can use this code i have tried it.It works.
this code will print the string "message". after the 3 second ,from the scheduling time. You can change the time your self according to you requirement.
import time, traceback
import threading
def every(delay,message, task):
next_time = time.time() + delay
time.sleep(max(0, next_time - time.time()))
task(message)
def foo(message):
print(message+" :foo", time.time())
def main(message):
threading.Thread(target=lambda: every(3,message, foo)).start()
main("message")

how to debug Tornado async operation

I am new to Tornado framework, and according to the link Asynchronous and non-Blocking I/O, I wrote some demo code as below. Unfortunately, the sync http client works, but async http client not. It looks like, the callback function that I passed to AsyncHTTPClient.fetch never has the chance to run. So my question is:
Why tornado's async API not work for me?
How should I debug this kind of problem? Set a break-point to my callback function is useless because it never has chance to run.
Any help is great appreciated. Below is my demo code:
from tornado.httpclient import AsyncHTTPClient
from tornado.httpclient import HTTPClient
import time
myUrl = 'a http url serving RESTful service'
def async_fetch(url, callback):
http_client = AsyncHTTPClient()
def handle_test(response):
callback(response.body)
http_client.fetch(url, handle_test)
def sync_fetch(url):
http_client = HTTPClient()
response = http_client.fetch(url)
return response.body
def printResponse(data):
print("response is:" + data)
def main():
sync_fetch(myUrl) #this works
async_fetch(myUrl, printResponse) #this not work
if __name__ == '__main__':
main()
print("begin of sleep!")
time.sleep(2)
print("end of sleep!")
You need to start the IOLoop, otherwise your asynchronous task never makes progress:
from tornado.ioloop import IOLoop
def printResponse(data):
print("response is:" + data)
IOLoop.current().stop()
def main():
sync_fetch(myUrl) #this works
async_fetch(myUrl, printResponse)
IOLoop.current().start()
In this example I stop the loop at the bottom of printResponse. In a real web server application you might never explicitly stop the loop.

Categories

Resources