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 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)
from apistar import App, Route from scraper_hb import get_data import os from new import crawl def welcome(name=None): if name is None: return {'message': 'Welcome to API Star!'} return {'message': 'Welcome to API Star, %s!' % name} def data(url): result = crawl(url) return result routes = [ Route('/', method='GET', handler=welcome), Route('/data/', method='GET', handler=data), ] app = App(routes=routes) if __name__ == '__main__': app.serve('159.89.8.122', 5000, debug=True)
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'])
def jsonify(records): """ Parse asyncpg record response into JSON format """ list_return = [] list_keys = ['salary', 'address', 'age', 'id', 'name'] for r in records: itens = [i for i in r] itens = zip(list_keys, itens) list_return.append({ i[0]: i[1].rstrip() if type(i[1]) == str else i[1] for i in itens }) return list_return routes = [ Route('/db2', method='GET', handler=db2), ] app = App(routes=routes) log = logging.getLogger('werkzeug') log.setLevel(logging.ERROR) if __name__ == '__main__': app.serve('127.0.0.1', 5000, use_debugger=False, use_reloader=False)
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)
page=page, page_size=page_size) resource_routes.register(PuppyResource, "/puppy") components = [PeeweeDatabaseComponent(url="sqlite:///demo.db")] event_hooks = [PeeweeTransactionHook] packages = ("apistar_crud", ) app = App(routes=resource_routes.routes(), components=components, event_hooks=event_hooks, packages=packages) if __name__ == "__main__": with components[0].database: components[0].database.create_tables([PuppyModel]) # Patching for autorefresh app.statics.whitenoise.autorefresh = True for package in packages or []: package_dir = os.path.dirname(find_spec(package).origin) package_dir = os.path.join(package_dir, "static") package_prefix = "/static/" + package app.statics.whitenoise.add_files(package_dir, prefix=package_prefix) app.document.title = "Demo" app.document.description = "API Star CRUD Demo" app.serve("0.0.0.0", 8000, debug=True)
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)
:param arg: <str> to choose modes from `new` or `get`. :param _id: <str> to fetch a certain match with the _id given. :param data: <dict> needed for creating new matches. :return: <obj> a Match object with data. ''' if arg == 'new': if not data: return 'need data to create new match!' else: match = Match(data) elif arg == 'get': if not _id: return 'need id to get match data!' else: match = Match(_id) return match def parse(image_file): pass routes = [ Route('/', method='GET', handler=welcome), ] app = App(routes=routes) if __name__ == '__main__': app.serve('127.0.0.1', 20185, debug=True)
service_lua_url = 'http://' + 'service-lua' + '/env' resp = requests.get(service_lua_url, headers=forwardHeaders) data_lua = resp.json() service_node_url = 'http://' + 'service-node' + '/env' resp = requests.get(service_node_url, headers=forwardHeaders) data_node = resp.json() return { "message": 'Python' + platform.python_version() + '----->' + data_lua['message'] + ', ' + data_node['message'] } def status(): return 'ok' routes = [ Route('/env', method='GET', handler=env), Route('/status', method='GET', handler=status), ] # event_hooks = [CustomHeadersHook] # app = App(routes=routes, event_hooks=event_hooks) app = App(routes=routes) logging.basicConfig(level=logging.DEBUG) if __name__ == '__main__': app.serve('0.0.0.0', 80, debug=True)
from .urls import routes from .settings import (DEV_SERVER_ADDR, DEV_SERVER_PORT, DEV_USE_DEBUGGER, DEV_USE_RELOADER) from apistar import App from apistar_cors_hooks import CORSRequestHooks custom_options = {"origin": "*"} event_hooks = [CORSRequestHooks(options=custom_options)] app = App(routes=routes, event_hooks=event_hooks) if __name__ == '__main__': app.serve(DEV_SERVER_ADDR, DEV_SERVER_PORT, use_debugger=DEV_USE_DEBUGGER, use_reloader=DEV_USE_RELOADER)
def edit_contact(email: str, update_contact: Contact) -> JSONResponse: contact = contacts.get(email) if not contact: error = {'error': CONTACT_NOT_FOUND} return JSONResponse(error, 404) contacts[email] = update_contact return JSONResponse(update_contact, status_code=200) def delete_contact(email: str) -> JSONResponse: contact = contacts.get(email) if not contact: error = {'error': CONTACT_NOT_FOUND} return JSONResponse(error, status_code=404) deleted_contact = contacts.pop(email) return JSONResponse(deleted_contact, status_code=204) routes = [ Route('/', method='GET', handler=get_all_contacts), Route('/', method='POST', handler=create_contact), Route('/{email}/', method='GET', handler=get_contact), Route('/{email}/', method='PUT', handler=edit_contact), Route('/{email}/', method='DELETE', handler=delete_contact) ] app = App(routes=routes) if __name__ == '__main__': app.serve('127.0.0.1', 5000)
def welcome() -> str: return "Welcome to the UNIX User API, consult your manual to get started." routes = [ Route('/', method='GET', handler=welcome), Route('/users/{uid}', method='GET', handler=user), Route('/users/{uid}/groups', method='GET', handler=ugroups), Route('/groups/{gid}', method='GET', handler=group), Route('/groups/query', method='GET', handler=gquery), Route('/users/query', method='GET', handler=uquery), Route('/users', method='GET', handler=ulist), Route('/groups', method='GET', handler=glist), ] app = App(routes=routes) if __name__ == '__main__': imap = ["host", "port", 'fpuser', 'fpgroup'] ##index map for dict if (len(sys.argv) == 1): print(f"No arguments supplied, using defaults: {fields}") for i, arg in enumerate(sys.argv[1:]): try: fields[imap[i]] = arg except: raise Exception( f"{arg} is not a valid {fields[imap[i]]} argument.") app.serve(fields["host"], int(fields["port"]), debug=True)
class ActionPiAPI(object): 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 _start_recording(self): self._camera.start_recording() def _stop_recording(self): self._camera.stop_recording() def _set(self, val: int): #TODO add more logic if needed in future self._camera.change_framerate(val) def _get_status(self) -> dict: return { 'system': { 'cpu_temperature': get_cpu_temp(), 'cpu_load': psutil.cpu_percent(interval=None), 'mem_usage': psutil.virtual_memory().percent, 'disk_usage': psutil.disk_usage('/').percent }, 'recording': self._camera.is_recording(), 'framerate': self._camera.get_framerate() } def _control(self): return self._api.render_template('index.html', app=app) def _halt(self): halt_system() def serve(self): self._api.serve(self._host, self._port, self._debug) def close(self): pass
# coding=utf-8 from apistar import Include, Route, App def hello(): return "Hello World!" routes = [ Route('/', 'GET', hello), ] app = App(routes=routes) if __name__ == '__main__': app.serve('127.0.0.1', 8888, debug=True)
from apistar import App, Route def hello() -> dict: return {"hello": "world"} routes = [Route("/", "GET", hello)] app = App(routes=routes) app.serve('127.0.0.1', 5000, debug=True)
from apistar import App, Include from project.hooks import Cors, MustBeAuthenticated from users.routes import routes as users_routes from users.models import UserComponent routes = [ Include('', name='users', routes=users_routes), ] event_hooks = [Cors, MustBeAuthenticated] components = [UserComponent()] app = App(routes=routes, event_hooks=event_hooks, components=components) if __name__ == '__main__': app.serve('0.0.0.0', 5000, debug=True)
if not data.get(username): return JSONResponse({'error': NOT_FOUND}, 404) prisoner.username = username data[username] = prisoner return JSONResponse(Prisoner(prisoner), 200) def remove_prisoner(username): ''' Deletes specified user ''' if not data.get(username): return JSONResponse({'error': NOT_FOUND}, 404) del data[username] return JSONResponse({}, 204) routes = [ Route('/', method='GET', handler=list_prisoners), Route('/', method='POST', handler=create_prisoner), Route('/{username}/', method='GET', handler=get_prisoner), Route('/{username}/', method='PUT', handler=update_prisoner), Route('/{username}/', method='DELETE', handler=remove_prisoner), ] app = App(routes=routes) if __name__ == '__main__': app.serve('localhost', 1234, debug=True)
from apistar import App, Include import custom_routes routes = [Include("/api", name="api", routes=custom_routes.routes),] app = App(routes) if __name__ == "__main__": app.serve("127.0.0.1", 9090, debug=True)
{'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}/', method='GET', handler=get_route, name='get_route_trailing_slash'), Route('/api/routes/{source}/', method='PUT', handler=update_route, name='update_route_trailing_slash'), Route('/api/routes/{source}/', method='DELETE', handler=delete_route, name='delete_route_trailing_slash'), ] app = App(routes=routes) if __name__ == '__main__': from ceryx import settings app.serve( settings.API_BIND_HOST, settings.API_BIND_PORT, use_debugger=settings.DEBUG, use_reloader=settings.DEBUG, )
error = {"error": MOVIE_NOT_FOUND} return JSONResponse(error, status_code=404) del movies[movie_id] return JSONResponse({}, status_code=204) def get_rating_greater_than(rating: float) -> JSONResponse: rating = float(rating) return sorted( [movie for movie in movies.values() if movie.get("rating") >= rating], key=lambda x: x.get("rating"), reverse=True, ) routes = [ Route("/", method="GET", handler=list_movies), Route("/", method="POST", handler=create_movie), Route("/{movie_id}/", method="GET", handler=get_movie), Route("/{movie_id}/", method="PUT", handler=update_movie), Route("/{movie_id}/", method="DELETE", handler=delete_movie), Route("/genre/{genre}/", method="GET", handler=list_movies_by_genre), Route("/rating/{rating}", method="GET", handler=get_rating_greater_than), ] app = App(routes=routes) if __name__ == "__main__": app.serve("127.0.0.1", 5000, debug=True)
from resource.todo import ROUTES as TODO_ROUTES from apistar import App, Include ROUTES = [ Include('/todos', name='users', routes=TODO_ROUTES), ] APP = App(routes=ROUTES) if __name__ == '__main__': APP.serve('127.0.0.1', 5000, debug=True)
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)
from apistar import App, Route def welcome(name=None): if name: return {"msg": "Welcome to API Star, %s" % name} else: return {"msg": "Welcome to API Star!"} routes = [Route("/", method="GET", handler=welcome)] app = App(routes=routes) if __name__ == "__main__": app.serve("0.0.0.0", 5000, debug=True) # serve on 0.0.0.0 for docker use
"/api/routes/{source}/", method="GET", handler=get_route, name="get_route_trailing_slash", ), Route( "/api/routes/{source}/", method="PUT", handler=update_route, name="update_route_trailing_slash", ), Route( "/api/routes/{source}/", method="DELETE", handler=delete_route, name="delete_route_trailing_slash", ), ] app = App(routes=routes) if __name__ == "__main__": from ceryx import settings app.serve( settings.API_BIND_HOST, settings.API_BIND_PORT, use_debugger=settings.DEBUG, use_reloader=settings.DEBUG, )
from apistar import App from routes import routes from components import components from event_hooks import event_hooks app = App(routes=routes, components=components, event_hooks=event_hooks) if __name__ == "__main__": default = {"host": "127.0.0.1", "port": 5000, "debug": True} app.serve(**default)
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)
if userid not in users: return JSONResponse(ERROR_USER_NOT_FOUND, HTTPStatus.NOT_FOUND) user.userid = userid user.joined = users[userid]["joined"] users[userid] = user return JSONResponse(User(user), HTTPStatus.OK) def delete_user(userid: int) -> JSONResponse: """Delete existing user.""" if userid not in users: return JSONResponse(ERROR_USER_NOT_FOUND, HTTPStatus.NOT_FOUND) users.pop(userid) return JSONResponse({}, HTTPStatus.NO_CONTENT) # ----------------------------------------------------------------------------- routes = [ Route("/", method="get", handler=get_users), Route("/{userid}", method="get", handler=get_user), Route("/", method="post", handler=create_user), Route("/{userid}", method="put", handler=update_user), Route("/{userid}", method="delete", handler=delete_user), ] app = App(routes=routes) if __name__ == "__main__": SERVER_IP = "127.0.0.1" SERVER_PORT = 5000 app.serve(SERVER_IP, SERVER_PORT, debug=True)
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 apistar import App from restpass import config from restpass import routes app = App(routes=routes.routes) if __name__ == '__main__': app.serve(config.DEV_SERVER_HOST, config.DEV_SERVER_PORT, debug=config.DEV_SERVER_DEBUG)