def create_app(config=None): """Create an apistar app from this factory.""" routes = create_routes() app = App( routes=routes, commands=commands, components=sqlalchemy_backend.components, settings=settings, ) return app
def app_fix(): """ fixture for apistar app Juste mock get_session to get_ss to disable db stuff from apistar Use all regular routes and componements of app.py All """ comp = [] for c in components: if c.cls is Session: c = Component(Session, init=get_ss, preload=False) comp.append(c) return App(routes=routes, settings=settings, components=comp)
def login(): routes = [ Route('/', 'GET', welcome), Include('/docs', docs_urls), Include('/static', static_urls) ] app = App(routes=routes) if __name__ == '__main__': app.main()
def attach_server(self, ksize=20, alpha=3, id=None, storage=None, *args, **kwargs): if not id: id = digest( secure_random(32)) # TODO: Network-wide deterministic ID generation (ie, auction or whatever) #136. super().attach_server(ksize, alpha, id, storage) routes = [ Route('/kFrag/{hrac_as_hex}', 'POST', self.set_policy), Route('/kFrag/{hrac_as_hex}/reencrypt', 'POST', self.reencrypt_via_rest), ] self._rest_app = App(routes=routes)
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('/consider_contract', 'POST', self.consider_contract), 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 attach_server(self, ksize=20, alpha=3, id=None, storage=None, *args, **kwargs): # TODO: Network-wide deterministic ID generation (ie, auction or # whatever) See #136. if not id: id = digest(secure_random(32)) super().attach_server(ksize, alpha, id, storage) 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('/consider_contract', 'POST', self.consider_contract), ] self._rest_app = App(routes=routes)
from apistar import Include, Route from apistar.frameworks.wsgi import WSGIApp as App from apistar.backends import sqlalchemy_backend from apistar.renderers import JSONRenderer from zones_api.models import Base from zones_api.urls import api_urls routes = [] routes += api_urls # Configure database settings. dbname = environ.get('POSTGRES_DB') dbuser = environ.get('POSTGRES_USER') dbhost = environ.get('POSTGRES_HOST') password = environ.get('POSTGRES_PASSWORD') settings = { "DATABASE": { "URL": f"postgresql://{dbuser}:{password}@{dbhost}/{dbname}", "METADATA": Base.metadata }, "RENDERERS": [JSONRenderer()] } app = App( routes=routes, settings=settings, commands=sqlalchemy_backend.commands, # Install custom commands. components=sqlalchemy_backend.components # Install custom components. )
def basic_untyped_list(things: UntypedList): return things def basic_typed_list(things: TypedList): return things routes = [ Route('/basic_typed_list/', 'POST', basic_typed_list), Route('/basic_untyped_list/', 'POST', basic_untyped_list), ] app = App(routes=routes) client = TestClient(app) def test_valid_untyped_list(): payload = [ 'foo', 'bar', 1, 3.1415927, 'baz', True, None, 'qux', ['tribbles'] * 23, {
def validate_length(value: MinMaxLength): return {'value': value} def validate_not_blank(value: NotBlank): return {'value': value} def validate_pattern(value: ValidPattern): return {'value': value} app = App(routes=[ Route('/length/', 'GET', validate_length), Route('/not_blank/', 'GET', validate_not_blank), Route('/pattern/', 'GET', validate_pattern), ]) client = TestClient(app) def test_valid_length(): response = client.get('/length/?value=abcde') assert response.status_code == 200 assert response.json() == {'value': 'abcde'} response = client.get('/length/?value=abcdefghij') assert response.status_code == 200 assert response.json() == {'value': 'abcdefghij'}
settings = { 'DATABASES': { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'db.sqlite3', } }, 'INSTALLED_APPS': [ 'core', 'django.contrib.auth', 'django.contrib.contenttypes', ], 'AUTHENTICATION': [BasicDjangoAuthentication()], } if os.environ.get('TEST'): settings['DATABASES']['default']['NAME'] = 'test.db.sqlite3' if os.environ.get('DEBUG'): routes.append(Include('/docs', docs_urls)) app = App( routes=routes, settings=settings, commands=django_orm.commands, components=django_orm.components, ) if __name__ == '__main__': app.main()
def welcome(name=None): if name is None: return {'message': 'Welcome to API Star!'} return {'message': 'Welcome to API Star, %s!' % name} routes = [ Route('/', 'GET', hello), Include('/docs', docs_urls), Include('/static', static_urls), Include('/playgound', bs_api.playground.routes), ] settings = { 'TEMPLATES': { 'ROOT_DIR': 'templates', # Include the 'templates' direcotry. 'PACKAGE_DIRS': ['apistar'], # Include the buildin apistar templates. }, 'AUTHENTICATION': [BasicAuthentication()] } app = App( routes=routes, commands=bs_api.playground.commands, settings=settings, ) if __name__ == '__main__': app.main()
# example products Route('/products', 'GET', products), Route('/cart/{id}', 'GET', detail_cart), Route('/cart/{id}', 'POST', modify_cart), Route('/cart/{id}', 'DELETE', remove_cart), Route('/cart/{id}/products', 'POST', add_product), Route('/cart/{id}/done', 'POST', done), # Route('/cart/{cart}/products/{product}', 'DELETE', remove_product), # Route('/cart/{cart}/products/{product}', 'PUT', update_product), # Route('/cart/{cart}/vouchers', 'POST', add_voucher), # Route('/cart/{cart}/vouchers/{voucher}', 'DELETE', remove_voucher), # Route('/cart/{cart}/vouchers/{voucher}', 'PUT', update_voucher), # Route('/cart/{cart}/promotion', 'POST', add_promotion), # Route('/cart/{cart}/promotion/{promotion}', 'DELETE', remove_promotion), # Route('/cart/{cart}/promotion/{promotion}', 'PUT', update_promotion), Include('/docs', docs_urls), Include('/static', static_urls) ] commands = [ Command('sign_product', sign_product), Command('unsign_product', unsign_product), ] app = App(routes=routes, commands=commands) if __name__ == '__main__': app.main()
import os import django from apistar.backends import django_orm # from apistar.backends import sqlalchemy_backend from apistar.frameworks.wsgi import WSGIApp as App # from apistar.frameworks.asyncio import ASyncIOApp as App os.environ['DJANGO_SETTINGS_MODULE'] = 'settings.apistar_base' django.setup() from settings import apistar_base import routes app = App( routes=routes.routes, settings=apistar_base.settings, commands=django_orm.commands, # Install custom commands. components=django_orm.components # Install custom components. # commands=sqlalchemy_backend.commands, # Install custom commands. # components=sqlalchemy_backend.components # Install custom components. ) if __name__ == '__main__': app.main()
Include('/docs', docs_urls), Include('', ui.routes), Route('/{path}', 'GET', serve_static), ] # The preceeding services also export components used to manipulate HTTP # requests and responses. from cadastre import authn from cadastre import document from cadastre import sql components = [ *sql.components, *authn.components, *document.components, ] # Finally, expose all of the endpoints, as well as supporting components, as an # API Star application. This can be bound to a WSGI framework and executed as a # web application - as gunicorn does. from apistar.frameworks.wsgi import WSGIApp as App from cadastre import config app = App( routes=routes, components=components, settings=config.settings, )
import os import tempfile import pytest from apistar import Component, exceptions from apistar.components.console import BufferConsole from apistar.frameworks.wsgi import WSGIApp as App from apistar.interfaces import Console components = [Component(Console, init=BufferConsole)] app = App(components=components) def test_new(): with tempfile.TemporaryDirectory() as tempdir: os.chdir(tempdir) app.main(['new', 'myproject', '--framework', 'wsgi'], standalone_mode=False) assert os.path.exists('myproject') assert os.path.exists(os.path.join('myproject', 'app.py')) assert os.path.exists(os.path.join('myproject', 'tests.py')) assert app.console.buffer.splitlines() == [ 'myproject/app.py', 'myproject/tests.py' ] def test_do_not_overwrite_existing_project(): with tempfile.TemporaryDirectory() as tempdir: os.chdir(tempdir) app.main(['new', 'myproject', '--framework', 'wsgi'],
from apistar.backends.django_orm import components as django_components from apistar.frameworks.wsgi import WSGIApp as App from authentication.utils import TokenAuthentication from config.settings import api_settings as django_settings from config.routes import routes app = App( routes=routes, settings={ **django_settings, 'AUTHENTICATION': [TokenAuthentication()], }, components=django_components, ) if __name__ == '__main__': app.main()
if not apps.ready: django.setup() # apistar configs, urls have to be imported AFTER django is ready apistar_settings = importlib.import_module('config.settings') # All routes are based on config.urls.routes routes = importlib.import_module('config.urls').routes # collect All components components = [ *django_orm.components, *apistar_shell_components.components, ] # Merge apistar and django settings, so everything is in Settings component # For testing and doc, this one bellow schould be imported settings = {**apistar_settings.__dict__, **django_settings.__dict__} print(settings['AUTHENTICATION']) # Collect all commands commands = [*django_orm.commands, *apistar_shell_commands.django_commands] app = App(routes=routes, settings=settings, commands=commands, components=components) if __name__ == '__main__': app.main()
import pytest from apistar import Route, TestClient, exceptions, typesystem from apistar.frameworks.wsgi import WSGIApp as App def get_boolean(value: typesystem.Boolean): return {'value': value} app = App(routes=[ Route('/boolean/', 'GET', get_boolean), ]) client = TestClient(app) def test_boolean(): assert typesystem.Boolean(1) is True assert typesystem.Boolean(0) is False assert typesystem.Boolean('1') is True assert typesystem.Boolean('0') is False assert typesystem.Boolean(True) is True assert typesystem.Boolean(False) is False assert typesystem.Boolean('TRUE') is True assert typesystem.Boolean('FALSE') is False def test_valid_boolean(): response = client.get('/boolean/?value=true')
class TermsAndConditions(typesystem.Enum): errors = {'invalid': 'You must agree to the terms and conditions to proceed.'} enum = ['yes'] def validate_color(value: Color): return {'value': value} def validate_terms(value: TermsAndConditions): return {'value': value} app = App(routes=[ Route('/color/', 'GET', validate_color), Route('/terms/', 'GET', validate_terms), ]) client = TestClient(app) def test_valid_enum(): response = client.get('/color/?value=red') assert response.status_code == 200 assert response.json() == {'value': 'red'} def test_valid_literal(): response = client.get('/terms/?value=yes') assert response.status_code == 200
# -*- coding: utf-8 -*- """APIStar Web App.""" import sys import apistar_peewee # https://github.com/aachurin/apistar_peewee from apistar.frameworks.wsgi import WSGIApp as App from routes import routes from settings import settings from apistar import Component from apistar_jwt.authentication import get_jwt from apistar_jwt.token import JWT __version__ = "1.0.0" __license__ = "???" __author__ = "???" __email__ = "*****@*****.**" __url__ = "https://example.com" sys.dont_write_bytecode = settings.get("DONT_WRITE_BYTECODE", True) # No *.PYC app: App = App( routes=routes, settings=settings, commands=apistar_peewee.commands, # Install custom commands. components=apistar_peewee.components + [Component(JWT, init=get_jwt)], ) if __name__ in '__main__': app.main()
Verify the identity of a user. """ return USERS.get((username, password), None) class Credentials(typesystem.Object): """ Structure for credentials in apistar. """ properties = { 'username': typesystem.String, 'password': typesystem.String, } def login(credentials: Credentials): """ Request to login an user. """ user = authenticate(credentials['username'], credentials['password']) if not user: return {'token': None} return {'token': jwt.encode(user, PRIVATE_KEY, algorithm='RS256').decode()} ROUTES = [ Route('/auth/login', 'POST', login), ] app = App(routes=ROUTES)
class MultipleInteger(typesystem.Integer): multiple_of = 10 def get_min_max(value: MinMaxInteger): return {'value': value} def get_multiple(value: MultipleInteger): return {'value': value} app = App(routes=[ Route('/min_max/', 'GET', get_min_max), Route('/multiple/', 'GET', get_multiple), ]) client = TestClient(app) def test_invalid_integer(): response = client.get('/min_max/?value=a') assert response.status_code == 400 assert response.json() == {'value': 'Must be a valid number.'} def test_valid_min_max(): response = client.get('/min_max/?value=3') assert response.status_code == 200 assert response.json() == {'value': 3}
def login(username: str, session: http.Session) -> dict: session["username"] = username or getuser() # Writes FAKE Data. session["last_login"] = datetime.utcnow().isoformat() # Writes FAKE Data. session["token"] = token_urlsafe() # Writes FAKE Data. print(session.data) # Reads Session Data. return session.data def logout(session: http.Session) -> dict: if session.data: # Clean out Session Data. del session["username"], session["last_login"], session["token"] return session.data routes = ( Route('/', 'GET', login), # Writes and Reads Session Data. Route('/logout', 'GET', logout), # Deletes Session Data. ) cookie_sessions = (Component(http.Session, init=init_cookie_session), ) app = App(routes=routes, components=cookie_sessions) if __name__ in '__main__': app.main()
""" if not user: return {'message': 'tsu tsu'} return {'message': f'you are a true user {user.username}'} def secret(user: User): """ A secret url of the service, only available for admin. """ if not user: return {'message': 'tsu tsu'} if not user.is_admin: return {'message': f'wont tell you ma secret {user.username}'} return { 'message': f'you are a true user {user.username}', 'secret': f'this is a super secret message', } ROUTES = [ Route('/service/protected', 'GET', protected), Route('/service/secret', 'GET', secret), ] COMPONENTS = [ Component(User, authenticate_user), ] app = App(routes=ROUTES, components=COMPONENTS)
routes = [ Route('/todo/', 'GET', list_todo), Route('/todo/', 'POST', add_todo), Route('/todo/{ident}/', 'GET', show_todo), Route('/todo/{ident}/', 'PUT', set_complete), Route('/todo/{ident}/percent_complete', 'PUT', set_percent_complete), Route('/todo/{ident}/category', 'PUT', set_category), Route('/docs/', 'GET', api_documentation), Route('/schema/', 'GET', serve_schema), Route('/schema.js', 'GET', javascript_schema), Route('/static/{path}', 'GET', serve_static) ] settings = {'SCHEMA': {'TITLE': 'My API'}} app = App(routes=routes, settings=settings) client = TestClient(app) expected = Schema( title='My API', url='/schema/', content={ 'list_todo': Link(url='/todo/', action='GET', description='list_todo description', fields=[ Field(name='search', location='query', required=False,
from api import routes def welcome(name=None): if name is None: return {'message': 'Welcome to db Star!'} return {'message': 'Welcome to db Star, %s!' % name} routes = routes + \ [ Include('/docs', docs_urls), Include('/static', static_urls) ] # Configure database settings settings = { "DATABASE": { "URL": "sqlite:///Test.db", "METADATA": Base.metadata } } app = App(routes=routes, settings=settings, commands=sqlalchemy_backend.commands, components=sqlalchemy_backend.components) if __name__ == '__main__': app.main()
from apistar import Route, Include from apistar.frameworks.wsgi import WSGIApp as App from apistar.handlers import docs_urls from view.user import user_auth, user_join def ping(): ''' :return: dict ''' return {"status": "ok"} routes = [ Route('/ping', 'GET', ping), # 認証 Route('/user/auth', "GET", user_auth), Route('/user/join', "POST", user_join), Include('/docs', docs_urls), ] app = App(routes=routes) # Install custom components.) if __name__ == "__main__": app.main(["run"])