def test_empty_response(): app = App(routes=[Route('/', 'GET', empty_response)]) client = TestClient(app) response = client.get('/') assert response.status_code == 204 assert response.text == '' assert 'Content-Type' not in response.headers
def test_unknown_status_code(): app = App(routes=[Route('/', 'GET', unknown_status_code)]) client = TestClient(app) response = client.get('/') assert response.status_code == 600 assert response.json() == {'hello': 'world'} assert response.headers['Content-Type'] == 'application/json'
def make_doc(directory): app = App(routes=routes) codec = codecs.OpenAPICodec() content = codec.encode(app.document) document = codec.decode(content) loader = jinja2.PrefixLoader( {"apistar": jinja2.PackageLoader("apistar", "templates")}) env = jinja2.Environment(autoescape=True, loader=loader) template = env.get_template("apistar/docs/index.html") code_style = None # pygments_css('emacs') output_text = template.render( document=document, langs=["javascript", "python"], code_style=code_style, static_url=lambda x: x, ) output_path = os.path.join(directory, "index.html") if not os.path.exists(directory): os.makedirs(directory) output_file = open(output_path, "w") output_file.write(output_text) output_file.close() static_dir = os.path.join(os.path.dirname(apistar.__file__), "static") apistar_static_dir = os.path.join(directory, "apistar") if os.path.exists(apistar_static_dir): shutil.rmtree(apistar_static_dir) shutil.copytree(static_dir, apistar_static_dir) print(f"Documentation built at {output_path}")
def web(debug=True, port=5000, host='127.0.0.1'): from apistar import App, Route routes = [ Route('/', method='GET', handler=homepage), ] app = App(routes=routes) app.serve(host, port, debug=debug)
def attach_rest_server(self, db_name): routes = [ Route('/kFrag/{hrac_as_hex}', 'POST', self.set_policy), Route('/kFrag/{hrac_as_hex}/reencrypt', 'POST', self.reencrypt_via_rest), Route('/public_keys', 'GET', self.get_signing_and_encrypting_public_keys), Route('/list_nodes', 'GET', self.list_all_active_nodes_about_which_we_know), Route('/consider_arrangement', 'POST', self.consider_arrangement), Route('/treasure_map/{treasure_map_id_as_hex}', 'GET', self.provide_treasure_map), Route('/treasure_map/{treasure_map_id_as_hex}', 'POST', self.receive_treasure_map), ] self._rest_app = App(routes=routes) self.start_datastore(db_name)
def __init__(self, camera: ActionPiCamera, host: str, port: int, debug=False): self._camera = camera self._host = host self._port = port self._debug = debug #Declaring routes _routes = [ Route('/api/start', method='GET', handler=self._start_recording), Route('/api/stop', method='GET', handler=self._stop_recording), Route('/api/status', method='GET', handler=self._get_status), Route('/api/set', method='GET', handler=self._set), Route('/api/halt', method='GET', handler=self._halt), Route('/control', method='GET', handler=self._control), ] #Serving static files base_dir = os.path.dirname(__file__) static_dir = os.path.join(base_dir, 'static') templates_dir = os.path.join(base_dir, 'templates') self._api = App(routes=_routes, static_dir=static_dir, template_dir=templates_dir)
def test_misconfigured_route(): def set_type(var: set ): # pragma: nocover (We never actually call this handler) pass with pytest.raises(exceptions.ConfigurationError): App(routes=[Route('/{var}/', 'GET', set_type)])
def make_app(): routes = [ Route('/', method='GET', handler=import_module("useapistar.views.welcome").welcome), Route('/cellar/accounts', method='GET', handler=import_module("useapistar.views.accounts").accounts), ] return App(routes=routes)
def main(): # pragma: no cover setup_pythonpath() try: app = get_current_app() except NoCurrentApp: app = App() try: app.click() except (NoCurrentApp, ConfigurationError) as exc: click.echo(str(exc)) sys.exit(1)
def run(self, *args, **kwargs): """ After building the object, this method needs to be called to run the server. This method will build the apistar `app` with the appropiate handlers and will serve it. It receives the same parameters as apistar App.serve method. More information here: https://github.com/encode/apistar/blob/master/apistar/server/app.py#L161 :raises ValueError: if the encoded data provided by the request does not include all the in_t placeholders. """ routes = [Route('/', method='POST', handler=self._make_inference)] app = App(routes=routes) app.serve(*args, **kwargs)
def test_lookup_cache_expiry(): """ Forcibly cycle the URL lookup cache, and ensure that we continue to generate correct lookups. """ def get_path(var: int, path: http.Path): return {'path': path} app = App(routes=[Route('/{var}/', 'GET', get_path)]) wsgi = get_wsgi_server(app, lookup_cache_size=3) client = TestClient(wsgi) for index in range(10): response = client.get('/%d/' % index) assert response.status_code == 200 assert response.json() == {'path': '/%d/' % index}
def test_lookup_cache_expiry(): """ Forcibly cycle the URL lookup cache, and ensure that we continue to generate correct lookups. """ def get_path(var: int, path: http.Path): return {'path': path} routes = [Route('/{var}/', 'GET', get_path)] settings = {'ROUTING': {'LOOKUP_CACHE_SIZE': 3}} app = App(routes=routes, settings=settings) client = TestClient(app) for index in range(10): response = client.get('/%d/' % index) assert response.status_code == 200 assert response.json() == {'path': '/%d/' % index}
def test_on_error_loads_the_same_component_instances(): # Given that I have an app that uses an AComponent and the AEventHooks app = App( components=[AComponent()], event_hooks=[AEventHooks], routes=[Route('/uses-a', method='GET', handler=uses_a)], ) # When I call an endpoint that raises an error with pytest.raises(RuntimeError): test.TestClient(app).get('/uses-a') # Then all the instances of A are the same assert len(A_INSTANCES) >= 2 for i in range(1, len(A_INSTANCES)): assert A_INSTANCES[i] is A_INSTANCES[i - 1]
def attach_rest_server(self): routes = [ Route('/kFrag/{id_as_hex}', 'POST', self.set_policy), Route('/kFrag/{id_as_hex}/reencrypt', 'POST', self.reencrypt_via_rest), Route('/public_information', 'GET', self.public_information), Route('/node_metadata', 'GET', self.all_known_nodes), Route('/node_metadata', 'POST', self.node_metadata_exchange), Route('/consider_arrangement', 'POST', self.consider_arrangement), Route('/treasure_map/{treasure_map_id}', 'GET', self.provide_treasure_map), Route('/treasure_map/{treasure_map_id}', 'POST', self.receive_treasure_map), ] self._rest_app = App(routes=routes) self.start_datastore(self.db_name)
def create_app(config=DefaultConfig): """Set-up the web API. :rtype: apistar.App """ if inspect.isclass(config): config = config() # To load configuration from environment variables database_url = f'{config.DATABASE_URL}' components = [SQLAlchemySessionComponent(url=database_url)] event_hooks = [SQLAlchemyTransactionHook()] return App( routes=routes, template_dir=str(TEMPLATES_DIR), components=components, event_hooks=event_hooks, )
def create_app(db_url: str): components = [ SQLAlchemySessionComponent(url=db_url), UserComponent(), ] event_hooks = [ AuthorizationHook(), SQLAlchemyTransactionHook(), ] # Create all SQL tables, if they do not exist. engine = components[0].engine database.Base.metadata.create_all(engine) app = App(routes=routes, components=components, event_hooks=event_hooks) app.debug = True return { "app": app, "engine": engine, "database": database, }
dislike_button = soup.find( 'button', class_='like-button-renderer-dislike-button-unclicked') statistics['dislikes'] = int(remove_comma(dislike_button.span.string)) # get uploader's name uploader_div = soup.find('div', class_='yt-user-info') uploader['name'] = uploader_div.a.get_text() # is the uploader verified? verified_span = uploader_div.span uploader['is_verified'] = verified_span is not None # get uploader's thumbnail URL uploader['thumbnail_url'] = soup.find( 'span', class_='yt-thumb-clip').img['data-thumb'] return RESPONSE return http.JSONResponse( {'error': 'Video with the ID {} does not exist'.format(id)}, status_code=404) routes = [ Route('/scrape', method='GET', handler=scrape_video_data), ] app = App(routes=routes) if __name__ == '__main__': app.serve('127.0.0.1', 5000, debug=True)
from wsgicors import CORS from apistar import App, Include from settings import jwt_settings from components.auth import Auth from middlewares import EventHookAuth from api import auth from api import users from api import status from api import features from api import services components = [Auth(jwt_settings)] event_hooks = [EventHookAuth()] routes = [ Include("/", name="Status", routes=status.routes), Include("/auth", name="Authentication", routes=auth.routes), Include("/users", name="User", routes=users.routes), Include("/features", name="Feature", routes=features.routes), Include("/services", name="Service", routes=services.routes), ] app = App(routes=routes, components=components, event_hooks=event_hooks) app = CORS(app, headers="*", methods="*", origin="*", maxage="86400")
def create_kitten(db: SQLAlchemy, name: http.QueryParam): session = db.session_class() add_kitten = Kitten(name=name) session.add(add_kitten) session.commit() created_kitten = add_kitten.serialize() session.close() return created_kitten app = App(routes=[ routing.Route('/kittens/create/', 'GET', create_kitten), routing.Route('/kittens/', 'GET', list_kittens), ], settings={ "DATABASE": { "URL": environ.get('DB_URL', 'sqlite:///test.db'), "METADATA": Base.metadata } }) client = test.TestClient(app) runner = CommandLineRunner(app) @pytest.fixture def clear_db(scope="function"): yield db_backend = SQLAlchemy.build(app.settings) db_backend.drop_tables()
from apistar import App from dynaconf import settings from routes import routes_configuration app = App(routes=routes_configuration, schema_url=settings.APP['schema_url'], template_dir=settings.TEMPLATE['dir'], static_dir=settings.TEMPLATE['static']) if __name__ == '__main__': app.serve(settings.SERVER['address'], settings.SERVER['port'], debug=settings.SERVER['debug'])
Route("/api/v1/redis/helloworld", method="GET", handler=hello_redis.get, name="redis_get"), Route("/api/v1/redis/helloworld", method="POST", handler=redis_post, name="redis_post"), Route("/api/v1/redis/helloworld", method="DELETE", handler=hello_redis.delete, name="redis_delete"), Route("/api/v1/mongo/helloworld", method="GET", handler=hello_mongo.get, name="mongo_get"), Route("/api/v1/mongo/helloworld", method="POST", handler=mongo_post, name="mongo_post"), Route("/api/v1/mongo/helloworld", method="DELETE", handler=hello_mongo.delete, name="mongo_delete") ] app = App(routes=routes, template_dir=TEMPLATE_DIR, static_dir=STATIC_DIR) if __name__ == '__main__': app.serve('0.0.0.0', 8000, use_debugger=True)
from apistar import App, Route, wsgi import ujson as json def json_view() -> wsgi.WSGIResponse: content = json.dumps({'message': 'Hello, world!'}).encode('utf-8') return wsgi.WSGIResponse('200 OK', [('Content-Type', 'application/json'), ('Content-Length', str(len(content)))], [content]) def plaintext_view() -> wsgi.WSGIResponse: content = b'Hello, world!' return wsgi.WSGIResponse('200 OK', [('Content-Type', 'text/plain'), ('Content-Length', str(len(content)))], [content]) app = App(routes=[ Route('/json', 'GET', json_view), Route('/plaintext', 'GET', plaintext_view), ])
def hello_world(): return {"hello": "world"} def error(): assert 1 == 2 routes = [ Route("/hello", method="GET", handler=hello_world), Route("/error", method="GET", handler=error), ] event_hooks = [CustomResponseHeader] app = App(routes=routes, event_hooks=event_hooks) client = test.TestClient(app) def test_on_response(): response = client.get("/hello") assert response.status_code == 200 assert response.headers["Custom"] == "Ran hooks" def test_on_error(): global ON_ERROR ON_ERROR = None with pytest.raises(AssertionError):
def app(): return App(routes=routes, components=components)
return {'var': var} def path_param_with_number(var: schema.Number): return {'var': var} def path_param_with_integer(var: schema.Integer): return {'var': var} app = App(routes=[ Route('/found/', 'GET', found), Route('/path_params/{var}/', 'GET', path_params), Route('/path_param/{var}/', 'GET', path_param), Route('/int/{var}/', 'GET', path_param_with_int), Route('/max_length/{var}/', 'GET', path_param_with_max_length), Route('/number/{var}/', 'GET', path_param_with_number), Route('/integer/{var}/', 'GET', path_param_with_integer), ]) client = TestClient(app) def test_200(): response = client.get('/found/') assert response.status_code == 200 assert response.json() == {'message': 'Found'} def test_404():
from apistar import App, Route, http, wsgi from apistar.test import TestClient def get_wsgi_environ(environ: wsgi.WSGIEnviron) -> http.Response: environ['wsgi.input'] = None return http.Response({'environ': environ}) def get_wsgi_response() -> wsgi.WSGIResponse: return wsgi.WSGIResponse('200 OK', [('Content-Type', 'application/json')], [b'{"hello": "world"}']) app = App(routes=[ Route('/wsgi_environ/', 'get', get_wsgi_environ), Route('/wsgi_response/', 'get', get_wsgi_response), ]) client = TestClient(app) def test_wsgi_environ(): response = client.get('http://example.com/wsgi_environ/') assert response.json() == { 'environ': { 'HTTP_ACCEPT': '*/*', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate', 'HTTP_CONNECTION': 'keep-alive', 'HTTP_HOST': 'example.com', 'HTTP_USER_AGENT': 'requests_client', 'PATH_INFO': '/wsgi_environ/',
with open('settings.html', 'r') as file: settings_html += file.read() index_content = '' with open('web/index.html', 'r') as file: index_content += file.read() result = index_content.replace('[spotify_html]', spotify_html) result = result.replace('[messenger_html]', messenger_html) result = result.replace('[settings_html]', settings_html) return result def appjs(): with open('web/app.js', 'r') as file: return file.read() routes = [ Route('/index.html', method='GET', handler=indexhtml), Route('/app.js', method='GET', handler=appjs), Route('/api/spotify/', method='GET', handler=SpotifyAPI), Route('/api/contactlist/', method='GET', handler=ContactListAPI), Route('/api/messenger/', method='GET', handler=MessengerAPI), ] web_dir = configsetup.get()['PATHS']['web_dir'] app = App(routes=routes, static_dir=web_dir, static_url='/web/') if __name__ == '__main__': md = MainDash() app.serve('127.0.0.1', 80, debug=True)
def app(): return App(routes=routes, event_hooks=event_hooks)
def test_misconfigured_route(): def set_type(var: set): # pragma: nocover pass with pytest.raises(exceptions.ConfigurationError): App(routes=[Route('/{var}/', 'GET', set_type)])
def path_param_with_integer(var: schema.Integer): return {'var': var} def subpath(var: schema.Integer): return {'var': var} app = App(routes=[ Route('/found/', 'GET', found), Route('/path_params/{var}/', 'GET', path_params), Route('/path_param/{var}/', 'GET', path_param), Route('/int/{var}/', 'GET', path_param_with_int), Route('/full_path/{var}', 'GET', path_param_with_full_path), Route('/max_length/{var}/', 'GET', path_param_with_max_length), Route('/number/{var}/', 'GET', path_param_with_number), Route('/integer/{var}/', 'GET', path_param_with_integer), Include('/subpath', [ Route('/{var}/', 'GET', subpath), ]), ]) client = TestClient(app) def test_200(): response = client.get('/found/') assert response.status_code == 200 assert response.json() == {'message': 'Found'}