Skip to content

Instantly share code, notes, and snippets.

@donatello
Last active June 7, 2018 13:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save donatello/0b399d0353cb29dc91b0 to your computer and use it in GitHub Desktop.
Save donatello/0b399d0353cb29dc91b0 to your computer and use it in GitHub Desktop.
Gevent + Request Session object Thread Safety Test
import gevent
from gevent.monkey import patch_all
patch_all()
import requests
import json
s = requests.Session()
def make_request(s, d):
r = s.post("http://127.0.0.1:5000", data=json.dumps({'value': d}))
if r.content.strip() != str(d*2):
print("Sent %s got %s" % (r.content, str(d*2)))
if r.status_code != 200:
print(r.status_code)
print(r.content)
gevent.joinall([
gevent.spawn(make_request, s, v)
for v in range(300)
])
Flask==0.10.1
Jinja2==2.7.2
MarkupSafe==0.23
Werkzeug==0.9.4
argparse==1.2.1
gevent==1.0.1
greenlet==0.4.2
gunicorn==18.0
itsdangerous==0.24
requests==2.3.0
wsgiref==0.1.2
from gevent.wsgi import WSGIServer
from gevent.monkey import patch_all
patch_all()
from flask import Flask
from flask import request
import time
import json
app = Flask(__name__)
@app.route('/', methods=['POST', 'GET'])
def hello_world():
d = json.loads(request.data)
return str(d['value']*2)
if __name__ == '__main__':
http_server = WSGIServer(('', 5000), app)
http_server.serve_forever()
@invalid-access
Copy link

Thanks for this code! I was wondering about the same thing. I inserted a time.sleep(random()*5) in the server's hello_world for good measure. Good to know Requests sessions are greenlet-safe.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment