Exemplo n.º 1
0
    return [
        {'id': album.id, 'title': album.title, 'year': album.year}
        for album in queryset
    ]


async def list_songs(session: Session):
    queryset = session.Song.objects.all()
    return [
        {'id': song.id, 'title': song.title, 'track': song.track}
        for song in queryset
    ]


routes = [
    Route('/', 'GET', welcome),
    Route('/albums/', 'GET', list_albums),
    Route('/albums/', 'POST', create_album),
    Route('/songs/', 'GET', list_songs),
    Route('/songs/', 'POST', create_song),
    Include('/docs', docs_urls),
    Include('/static', static_urls)
]

app = App(
    routes=routes,
    settings=settings,
    commands=django_orm.commands,
    components=django_orm.components
    )
Exemplo n.º 2
0
def test_object_headers():
    app = App(routes=[Route('/', 'GET', object_headers)])
    client = TestClient(app)
    response = client.get('/')
    assert response.headers['Content-Language'] == 'de'
Exemplo n.º 3
0
Arquivo: app.py Projeto: wajika/ceryx
            'settings': ROUTER.lookup_settings(source),
        }
        ROUTER.delete(source)
        return http.JSONResponse(
            types.Route(route),
            status_code=204,
        )
    except RedisRouter.LookupNotFound:
        return http.JSONResponse(
            {'message': f'Route with source {source} doesn\'t exist'},
            status_code=404,
        )


routes = [
    Route('/api/routes', method='GET', handler=list_routes),
    Route('/api/routes', method='POST', handler=create_route),
    Route('/api/routes/{source}', method='GET', handler=get_route),
    Route('/api/routes/{source}', method='PUT', handler=update_route),
    Route('/api/routes/{source}', method='DELETE', handler=delete_route),

    # Allow trailing slashes as well (GitHub style)
    Route('/api/routes/',
          method='GET',
          handler=list_routes,
          name='list_routes_trailing_slash'),
    Route('/api/routes/',
          method='POST',
          handler=create_route,
          name='create_route_trailing_slash'),
    Route('/api/routes/{source}/',
Exemplo n.º 4
0
def daemon_status():
    return {'message': raincollector.describe()}


def station_status(query: str):
    stations = raincollector.search(query)
    if stations:
        data = [{f'{rs.name}': rs.describe()} for rs in stations]
    return {'results': data}


def list_stations():
    stations = [s.to_dict() for s in raincollector.stations]
    return {'results': stations}


routes = [
    Route('/', 'GET', welcome),
    Route('/daemon/start', 'POST', start_daemon),
    Route('/daemon/status', 'GET', daemon_status),
    Route('/stations/', 'GET', list_stations),
    Route('/stations/{query}', 'GET', station_status),
    Include('/docs', docs_urls),
    Include('/static', static_urls)
]

app = App(routes=routes)

if __name__ == '__main__':
    app.main()
Exemplo n.º 5
0
def test_text_response():
    app = App(routes=[Route('/', 'GET', text_response)])
    client = TestClient(app)
    response = client.get('/')
    assert response.text == '<html><h1>Hello, world</h1></html>'
    assert response.headers['Content-Type'] == 'text/html; charset=utf-8'
Exemplo n.º 6
0
import os
from apistar import App, Route

BASE_DIR = os.path.dirname(__file__)
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')


def welcome(app: App, name=None):
    return app.render_template('index.php', name=name)


routes = [
    Route('/', method='GET', handler=welcome),
]

app = App(routes=routes, template_dir=TEMPLATE_DIR)

if __name__ == '__main__':
    app.serve('192.168.10.190', 5000, use_debugger=True)
def delete_season(season_id: str):
    batter = batters.get(season_id)
    if not batter:
        error = {'error': SEASON_NOT_FOUND}
        return JSONResponse(error, status_code=404)

    del batters[season_id]
    return JSONResponse({}, 204)


def create_season(season: Season):
    season_id = season['playerID'] + str(season['yearID']) + str(
        season['stint'])
    batters[season_id] = season
    return JSONResponse(Season(season), 201)


routes = [
    Route('/', method='GET', handler=list_seasons),
    Route('/', method='POST', handler=create_season),
    Route('/{season_id}/', method='GET', handler=get_season),
    Route('/{season_id}/', method='PUT', handler=update_season),
    Route('/{season_id}/', method='DELETE', handler=delete_season),
]

app = App(routes=routes)

if __name__ == '__main__':
    app.serve('127.0.0.1', 5000, debug=True)
Exemplo n.º 8
0
    p = persons.get(person_id)
    if not p:
        error = {'error': PERSON_NOT_FOUND}
        return JSONResponse(error, status_code=404)
    person.id = person_id
    persons[person_id] = Person(person)
    return JSONResponse(Person(person), 201)


def delete_employe(person_id: int) -> JSONResponse:
    p = persons.get(person_id)
    if not p:
        error = {'error': PERSON_NOT_FOUND}
        return JSONResponse(error, status_code=404)
    del (persons[person_id])
    return JSONResponse({}, 204)


routes = [
    Route('/', method='GET', handler=list_employes),
    Route('/', method='POST', handler=add_employe),
    Route('/{person_id}/', method='GET', handler=get_employe),
    Route('/{person_id}/', method='PUT', handler=update_employe),
    Route('/{person_id}/', method='DELETE', handler=delete_employe),
]

app = App(routes=routes)

if __name__ == '__main__':
    app.serve('127.0.0.1', 5000, debug=True)
Exemplo n.º 9
0
    return app.render_template(
        'form.html',
        show_csrf=False,
    )


def handle_form(request: http.Request):
    # You should rotate CSRF tokens after successful login/logout
    rotate_token(request)
    return app.render_template(
        'form.html',
        show_csrf=True,
        success=True,
    )


routes = [
    Route('/', 'GET', show_form),
    Route('/no_csrf', 'GET', show_no_csrf_form),
    Route('/handle', 'POST', handle_form),
]

BASE_DIR = os.path.dirname(__file__)
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')

app = App(
    routes=routes,
    event_hooks=[EnforceCsrfHook],
    template_dir=TEMPLATE_DIR,
)
Exemplo n.º 10
0
from apistar import Include, Route
from apistar.docs import docs_routes
from apistar.statics import static_routes
from project.views import create_poll, create_choices

routes = [
    # API to create Polls
    Route('/create_poll', 'POST', create_poll),
    # API to add choices to the polls
    Route('/create_choices', 'POST', create_choices),
    #Route('/students', 'GET', students)
]
Exemplo n.º 11
0
from .models import Token, User
from .validators import UUID


class TokenType(types.Type):
    id = UUID()
    user_id = validators.Integer()

    created = validators.DateTime()
    updated = validators.DateTime()


@authorized
def list_tokens(session: Session, user: User) -> List[TokenType]:
    tokens = session.query(Token).filter(Token.user_id == user.id).all()
    return list(map(TokenType, tokens))


@authorized
def create_token(session: Session, user: User) -> http.JSONResponse:
    with session.begin_nested():
        token = Token(user=user)
        session.add(token)
    return http.JSONResponse(TokenType(token), status_code=201)


routes = [
    Route('/tokens', 'GET', list_tokens),
    Route('/tokens', 'POST', create_token),
]
Exemplo n.º 12
0
    if data.email != USERS_DB['email'] or data.password != USERS_DB['password']:
        raise exceptions.Forbidden('Incorrect username or password.')
    payload = {
        'id': USERS_DB['id'],
        'username': USERS_DB['email'],
        'iat': datetime.datetime.utcnow(),
        'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60)  # ends in 60 minutes
    }
    token = jwt.encode(payload)
    if token is None:
        # encoding failed, handle error
        raise exceptions.BadRequest()
    return {'token': token}


routes = [
    Route('/', method='GET', handler=welcome),
    Route('/login', method='POST', handler=login),
]

components = [
    JWT({
        'JWT_SECRET': 'BZz4bHXYQD?g9YN2UksRn7*r3P(eo]P,Rt8NCWKs6VP34qmTL#8f&ruD^TtG',
    }),
]

app = App(routes=routes, components=components)

if __name__ == '__main__':
    app.serve('127.0.0.1', 8080, use_debugger=True, use_reloader=True)
Exemplo n.º 13
0
    return None


def unknown_status_code() -> http.Response:
    data = {'hello': 'world'}
    return http.Response(data, status=600)


def response_headers() -> http.Response:
    data = {'hello': 'world'}
    headers = {'Content-Language': 'de'}
    return http.Response(data, headers=headers)


routes = [
    Route('/request/', 'GET', get_request),
    Route('/method/', 'GET', get_method),
    Route('/method/', 'POST', get_method, name='post_method'),
    Route('/scheme/', 'GET', get_scheme),
    Route('/host/', 'GET', get_host),
    Route('/port/', 'GET', get_port),
    Route('/path/', 'GET', get_path),
    Route('/query_string/', 'GET', get_query_string),
    Route('/query_params/', 'GET', get_query_params),
    Route('/page_query_param/', 'GET', get_page_query_param),
    Route('/url/', 'GET', get_url),
    Route('/body/', 'POST', get_body),
    Route('/stream/', 'POST', get_stream),
    Route('/data/', 'POST', get_data),
    Route('/headers/', 'GET', get_headers),
    Route('/headers/', 'POST', get_headers, name='post_headers'),
Exemplo n.º 14
0
from aws_xray_sdk.core.context import Context
from tests.utils import get_new_stubbed_recorder




def all_good():
    return {'all':'good'}


def oh_noes():
    assert 'oh' == 'noes!'


routes = [
    Route('/all-good', method='GET', handler=all_good),
    Route('/oh-noes', method='GET', handler=oh_noes)
]


recorder = get_new_stubbed_recorder()
recorder.configure(service='test', sampling=False, context=Context())


event_hooks = [AWSXrayEventHook(recorder)]

app = App(routes=routes, event_hooks=event_hooks)

client = test.TestClient(app)

Exemplo n.º 15
0
    if not jobs.get(job_id):
        error = {'error' : JOB_NOT_FOUND}
        return JSONResponse(Job(job), status_code=404)
    job.id = job_id
    jobs[job_id] = job
    return JSONResponse(Job(job), status_code=200)

def delete_job(job_id: int) -> JSONResponse:
    if not jobs.get(job_id):
        error = {'error', JOB_NOT_FOUND}
        return JSONResponse(error, status_code=404)
    del jobs[job_id]
    return JSONResponse({}, status_code=204)

routes = [
    Route('/', method='GET', handler=list_jobs),
    Route('/', method='POST', handler=create_job),
    Route('/{job_id}/', method='GET', handler=get_job),
    Route('/{job_id}/', method='PUT', handler=update_job),
    Route('/{job_id}/', method='DELETE', handler=delete_job),

]

app = App(routes=routes)

if __name__ == '__main__':
    app.serve('127.0.0.1', 5000, debug=True)



            # strict one-form programs (zero-form programs and n-form programs
            # are both legal), easing the burden of annotating messages.
            program = session.read(port)
            while program != ar.EOF:
                session.eval(program)
                program = session.read(port)

        except Exception as e:
            exception_warning = dict(
                message=str(e),
            )
            warnings.append(annotate_dict(annotation, exception_warning))

        assert state == session.state
        warnings.extend(annotate_dict(annotation, w) for w in session.warnings)
        events.extend(annotate_dict(annotation, e) for e in session.events)

    # Glue the results into a response.
    return dict(events=events, state=state, warnings=warnings)

# ## WEB APPLICATION CONFIGURATION

# Annotations have a set of related API routes, which will all be mounted
# together. The root of this collection is the state computation endpoint.

from apistar import Route

routes = [
    Route('', 'GET', compute_state),
]
Exemplo n.º 17
0
from apistar import Include, Route
from apistar.handlers import docs_urls, static_urls, serve_static
from apps.details import detail_routes
from apps.files import file_routes
from apps.users import user_routes
from apps.login import login, logout
from apps.index import index

api_routes = [
    Include('/details', detail_routes),
    Include('/files', file_routes),
    Include('/users', user_routes),
    Route('/login', 'POST', login),
    Route('/logout', 'GET', logout),
]

routes = [
    Include('/api', api_routes),
    Include('/docs', docs_urls),
    Route('/dist/{path}', 'GET', serve_static),
    Route('/', 'GET', index),
    # Include('/static', static_urls)
]

for path in ('/details', '/login', '/fileList', '/admin'):
    routes.append(Route(path, 'GET', index, name=path))
Exemplo n.º 18
0
from apistar import Include, Route
from apistar.frameworks.asyncio import ASyncIOApp as App
from apistar.handlers import docs_urls, static_urls
from apistar.backends import sqlalchemy_backend
from project.models import Base
from project.routes import user_routes


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', welcome),
    Include('/docs', docs_urls),
    Include('/static', static_urls),
    Include('/users', user_routes)
]

settings = {

    "DATABASE": {
        "URL": "mysql+pymysql://root:qw010203@localhost/apistar",
        "METADATA": Base.metadata
    }
}

app = App(
    routes=routes,
Exemplo n.º 19
0
    output = {'valid': valid, 'execution_time': end_time - start_time}

    if not valid:
        output.update({'failed_block': BlockType(b)})

    return output


def tamper() -> BlockType:
    """
    Test endpoint that will manipulate the data of a random block.  This will
    cause the validation endpoint to fail.
    """
    random_block = random.choice(the_blockchain)
    random_block.data = {"foo": "bar"}

    return BlockType(random_block)


routes = [
    Route('/', method='GET', handler=chain),
    Route('/block', method='POST', handler=add_block),
    Route('/validate', method='GET', handler=validate_chain),
    Route('/tamper', method='GET', handler=tamper)
]

app = App(routes=routes)

if __name__ == '__main__':
    app.serve('127.0.0.1', 5000, debug=True)
Exemplo n.º 20
0
        "username": user.username,
        "iat": pendulum.now(),
        "exp": pendulum.now() + pendulum.Duration(seconds=1000),
    }
    token = jwt.encode(payload)
    if token is None:
        raise exceptions.ConfigurationError("échec de l'encodage jwt")

    return token


routes_users = Include(
    url="/users",
    name="users",
    routes=[
        Route(url="/login/", method="POST", handler=login, name="login"),
        # Route(url="/", method="GET", handler=liste),
        # Route(url="/{id}/", method="PUT", handler=update),
        # # Route(url="/patients/", method="DELETE", handler=delete),
        # Route(url="/{id}/", method="DELETE", handler=delete),
        # Route(url="/{id}/", method="GET", handler=get),
    ],
)
"""
# MEDECIN = "medecin"
# SECRETAIRE = "secretaire"
# INTERNE = "interne"
# REMPLACANT = "remplacant"
# STATUT = (
#     (MEDECIN, 'Médecin'),
#     (SECRETAIRE, 'Secrétaire'),
Exemplo n.º 21
0
from apistar import App, Route
from apistar import http, wsgi
from apistar.test import TestClient


def get_wsgi_environ(environ: wsgi.WSGIEnviron) -> http.Response:
    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',
def update_device(device_id: int, device: Device) -> http.JSONResponse:
    if not devices.get(device_id):
        return http.JSONResponse({'error': 'no device'}, status_code=404)
    device.id = device_id
    return http.JSONResponse(Device(device), status_code=200)


def delete_device(device_id: int) -> http.JSONResponse:
    if not devices.get(device_id):
        return http.JSONResponse({'error': 'no device'}, status_code=404)
    del devices[device_id]
    return http.JSONResponse({}, status_code=204)


# CRUD routes

routes = [
    Route('/', method='GET', handler=read_all_devices),
    Route('/', method='POST', handler=create_new_device),
    Route('/{device_id}/', method='GET', handler=read_device),
    Route('/{device_id}/', method='PUT', handler=update_device),
    Route('/{device_id}/', method='DELETE', handler=delete_device),
]

# create application

my_app = App(routes=routes)

if __name__ == '__main__':
    my_app.serve('127.0.0.1', 5050, debug=True)
Exemplo n.º 23
0

def get_accept_header(accept: http.Header) -> http.Response:
    return http.Response({'accept': accept})


def get_request(request: http.Request) -> http.Response:
    return http.Response({
        'method': request.method,
        'url': request.url,
        'headers': dict(request.headers)
    })


app = App(routes=[
    Route('/method/', 'GET', get_method),
    Route('/method/', 'POST', get_method),
    Route('/scheme/', 'GET', get_scheme),
    Route('/host/', 'GET', get_host),
    Route('/port/', 'GET', get_port),
    Route('/mount_path/', 'GET', get_mount_path),
    Route('/relative_path/', 'GET', get_relative_path),
    Route('/path/', 'GET', get_path),
    Route('/query_string/', 'GET', get_query_string),
    Route('/query_params/', 'GET', get_query_params),
    Route('/page_query_param/', 'GET', get_page_query_param),
    Route('/url/', 'GET', get_url),
    Route('/body/', 'POST', get_body),
    Route('/data/', 'POST', get_data),
    Route('/field/', 'POST', get_field),
    Route('/headers/', 'GET', get_headers),
Exemplo n.º 24
0
def list_puppies() -> List[PuppyType]:
    return [PuppyType(puppy) for puppy in PuppyModel.select()]


def create_puppy(puppy: PuppyType, raise_exception: http.QueryParam) -> http.JSONResponse:
    if raise_exception:
        raise Exception

    model = PuppyModel.create(**puppy)
    return http.JSONResponse(PuppyType(model), status_code=201)


database_component = PeeweeDatabaseComponent(url="sqlite+pool://")
components = [database_component]
event_hooks = [PeeweeTransactionHook]
routes = [Route("/puppy/", "POST", create_puppy), Route("/puppy/", "GET", list_puppies)]

app = App(
    routes=routes, components=components, event_hooks=event_hooks, static_dir=None, docs_url=None, schema_url=None
)
async_app = ASyncApp(
    routes=routes, components=components, event_hooks=event_hooks, static_dir=None, docs_url=None, schema_url=None
)


class TestCaseEndToEnd:
    @pytest.fixture(params=[app, async_app])
    def client(self, request):
        with database_component.database:
            database_component.database.create_tables([PuppyModel])
        yield TestClient(request.param)
Exemplo n.º 25
0
def test_data_response():
    app = App(routes=[Route('/', 'GET', data_response)])
    client = TestClient(app)
    response = client.get('/')
    assert response.json() == {'hello': 'world'}
    assert response.headers['Content-Type'] == 'application/json'
Exemplo n.º 26
0
    "id": "59011602",
    "firstname": "Peeranat",
    "lastname": "Limpitaporn"
}, {
    "id": "59011604",
    "firstname": "Phison",
    "lastname": "Khankang"
}, {
    "id": "59011605",
    "firstname": "Thirawat",
    "lastname": "Rungrotchaiyaporn"
}]


def get_student(std_id):
    for i in list:
        if std_id == i['id']:
            return (i)


def get_all():
    return (list)


routes = {
    Route('/id/{std_id}', 'GET', get_student),
    Route('/students', 'GET', get_all)
}

app = App(routes=routes, settings=settings, commands=[create_tables])
Exemplo n.º 27
0
def list_cars() -> List[Car]:
    return [car[1] for car in sorted(cars.items())]


def get_car(car_id: int) -> JSONResponse:
    car = cars.get(car_id)
    if not car:
        error = {'error': CAR_NOT_FOUND}
        return JSONResponse(error, status_code=404)

    return JSONResponse(Car(car), status_code=200)


def create_car(car: Car) -> JSONResponse:
    car_id = max(cars.keys()) + 1
    car.id = car_id
    cars[car_id] = car

    return JSONResponse(Car(car), status_code=201)


routes = [
    Route('/', method='GET', handler=list_cars),
    Route('/', method='POST', handler=create_car),
    Route('/{car_id}/', method='GET', handler=get_car),
]

app = App(routes=routes)

if __name__ == '__main__':
    app.serve('127.0.0.1', 5000, debug=True)
Exemplo n.º 28
0
    access_token = data.get('access_token')
    refresh_token = data.get('refresh_token')
    cred = TraktCred(user_id=user.id,
                     access_token=access_token,
                     refresh_token=refresh_token)
    session.add(cred)


def fetch_auth_code(code: str = None,
                    state: str = None) -> Union[str, http.Response]:
    if not code:
        return "no is no\nbut it's fine, i understand\nmaybe next time (:"

    telegram_id = check_state(state)
    if not telegram_id:
        return http.Response(
            "wow, this is very bad state in ur url. don't do that again",
            status_code=400)
    url = api_url('oauth/token')
    res = requests.post(url, json=params_for_token(code=code))
    data = res.json()
    save_credentials(telegram_id, data)
    bot = Bot(TELEGRAM_BOT_TOKEN)
    bot.send_message(telegram_id, 'subscribed to trakt')
    return 'everything is fine, my dude, u may close this tab now and jump back to the bot'


trakt_routes = [
    Route('/auth/', method='GET', handler=fetch_auth_code),
]
Exemplo n.º 29
0
    try:
        route = {
            "source": source,
            "target": ROUTER.lookup(source),
            "settings": ROUTER.lookup_settings(source),
        }
        ROUTER.delete(source)
        return http.JSONResponse(types.Route(route), status_code=204)
    except RedisRouter.LookupNotFound:
        return http.JSONResponse(
            {"message": f"Route with source {source} doesn't exist"},
            status_code=404)


routes = [
    Route("/api/routes", method="GET", handler=list_routes),
    Route("/api/routes", method="POST", handler=create_route),
    Route("/api/routes/{source}", method="GET", handler=get_route),
    Route("/api/routes/{source}", method="PUT", handler=update_route),
    Route("/api/routes/{source}", method="DELETE", handler=delete_route),
    # Allow trailing slashes as well (GitHub style)
    Route(
        "/api/routes/",
        method="GET",
        handler=list_routes,
        name="list_routes_trailing_slash",
    ),
    Route(
        "/api/routes/",
        method="POST",
        handler=create_route,
Exemplo n.º 30
0
from apistar import App, Route


def welcome(name=None):
    if name is None:
        return {"message": "Welcome to API Star!"}
    return {"message": "Welcome to Docker hell, %s!" % name}


routes = [Route("/", method="GET", handler=welcome)]

app = App(routes=routes)


if __name__ == "__main__":
    app.serve("0.0.0.0", 5000, debug=True)