Skip to content

Instantly share code, notes, and snippets.

@jaraco
Created November 29, 2017 22:33
Show Gist options
  • Save jaraco/d654d01eeeb64a1758eb0a60661e5bbf to your computer and use it in GitHub Desktop.
Save jaraco/d654d01eeeb64a1758eb0a60661e5bbf to your computer and use it in GitHub Desktop.
__requires__ = [
'flask>=0.12.2',
'flask-restful>=0.3.6',
'requests_toolbelt',
'autocommand',
]
import contextlib
from requests_toolbelt import sessions
from autocommand import autocommand
import cherrypy
from flask import Flask
from flask_restful import Api, Resource, reqparse, http_status_message
def build_app():
app = Flask(__name__)
api = Api(app)
@app.route('/')
def index():
return http_status_message(200)
class Hello(Resource):
def __init__(self):
self.parser = reqparse.RequestParser()
self.parser.add_argument('name', type=str, default='World')
def get(self):
args = self.parser.parse_args()
return 'Hello, {name}! Nice to meet you'.format(name=args['name'])
api.add_resource(Hello, '/hello', endpoint='hello')
return app
class ServerContext(contextlib.ContextDecorator):
def __enter__(self):
cherrypy.tree.graft(build_app(), '/')
cherrypy.config.update({
'environment': 'embedded',
'engine.autoreload.on': False,
'server.socket_port': 0,
})
cherrypy.engine.start()
def __exit__(self, *args):
cherrypy.engine.stop()
cherrypy.engine.exit()
@autocommand(__name__)
@ServerContext()
def run():
host, port = cherrypy.server.bound_addr
url = f'http://localhost:{port}/'
session = sessions.BaseUrlSession(url)
print('first a get')
resp = session.request('GET', '/hello')
resp.raise_for_status()
print('then options no params')
resp = session.request('OPTIONS', '/hello')
resp.raise_for_status()
print('then options with params')
resp = session.request('OPTIONS', '/hello?name=test')
resp.raise_for_status()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment