def main(): app = Application() r = app.router r.add_route('/sync', synchronous) r.add_route('/async', asynchronous) app.run('localhost', 5000)
def start(self): self.init_self() app = Application() app.router.add_route('/init', self.init_server, methods=['POST']) app.router.add_route('/balance', self.check_balance, methods=['POST']) app.router.add_route('/txstatus', self.check_txstatus, methods=['POST']) app.router.add_route('/', self.handle_message, methods=['POST']) app.run(host=self.address, port=self.port) return self.address, self.port
class JapApp(object): def __init__(self, host: str = '0.0.0.0', port: int = 9876, debug: bool = True, worker_num: int = multiprocessing.cpu_count(), log: str = '', conf: str = ''): self.host = host self.port = port self.debug = debug self.workerNum = worker_num self.app = None self.log = log self.logger = None self.initApp() self.initLog() def initApp(self): if self.app == None: self.app = Application() def initLog(self): if self.logger == None and self.log != '': self.logger = Log(self.log) def getLogger(self): self.initLog() return self.logger def run(self): self.initApp() self.app.run(host=self.host, port=self.port, debug=self.debug, worker_num=self.workerNum) def route(self, path, className): className.setLogger(self.getLogger()) self.app.router.add_route(path, className().deal)
from japronto import Application def hello(request): return request.Response(text='Hello world!') app = Application() app.router.add_route('/', hello) app.run(host='127.0.0.1', port=7777)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Project : tql-Python. # @File : plus # @Time : 2019-08-29 13:57 # @Author : yuanjie # @Email : [email protected] # @Software : PyCharm # @Description : from japronto import Application def hello(request): return request.Response(text='Hello world!') app = Application() app.router.add_route('/', hello) app.run(debug=True, port=7766)
import datetime import time from japronto import Application def main(request): time.sleep(1) return request.Response( json={ "Name": "Vinicius Pacheco", "ConsultedAt": datetime.datetime.now().strftime( '%Y-%m-%d %H:%M:%S'), }) app = Application() app.router.add_route('/', main) app.run(worker_num=20, port=5001)
for i in itens }) return list_return def index(request): data = {'message': 'hello world'} body = ujson.dumps(data) return request.Response(text=body) async def setup_db(loop): return await create_pool(**DB_CONFIG, loop=loop, max_size=25) async def db(request): async with request.app.db.acquire() as conn: results = await conn.fetch( 'SELECT salary,address,age,id,name FROM test.company') # return response.json({'posts': results}) body = ujson.dumps({'posts': jsonify(results)}) return request.Response(text=body, headers={'Content-Type': 'application/json'}) app = Application() app.db = app.loop.run_until_complete(setup_db(app.loop)) app.router.add_route('/', index) app.router.add_route('/db2', db) app.run(port=8001) # ,worker_num=4)
class LoggingServer: def __init__(self, data_dir): assert os.path.isabs(data_dir) self.data_dir = data_dir os.makedirs(data_dir, exist_ok=True) print('logging data to {}'.format(data_dir)) configure = __init__ def serve(self, port): from japronto import Application self.app = Application() self.app.router.add_route('/', self.log_handler, method='POST') self.app.router.add_route('/', self.read_handler, method='GET') self.app.router.add_route('/ping', self.ping_handler, method='POST') self.app.router.add_route('/', self.remove_handler, method='DELETE') # todo: need a file serving url self.app.run(port=port, debug=Params.debug) def ping_handler(self, req): if not req.json: msg = f'request json is empty: {req.text}' print(msg) return req.Response(text=msg) ping_data = PingData(**req.json) print("received ping data: {} type: {}".format(ping_data.status, ping_data.exp_key)) data = self.ping(ping_data.exp_key, ping_data.status, ping_data.burn) return req.Response(text=data) def ping(self, exp_key, status, burn=True): status_path = os.path.join(exp_key, '__presence') self.log(status_path, dict(status=status, time=datetime.now()), dtype="yaml", options=LogOptions(overwrite=True, write_mode='key')) signal_path = os.path.join(exp_key, '__signal.pkl') res = self.load(signal_path, 'read_pkl') if burn: self.remove(signal_path) return serialize(res) def read_handler(self, req): if not req.json: msg = f'request json is empty: {req.text}' print(msg) return req.Response(text=msg) load_entry = LoadEntry(**req.json) print("loading: {} type: {}".format(load_entry.key, load_entry.type)) res = self.load(load_entry.key, load_entry.type) data = serialize(res) return req.Response(text=data) def remove_handler(self, req): if not req.json: msg = f'request json is empty: {req.text}' print(msg) return req.Response(text=msg) remove_entry = RemoveEntry(**req.json) print("removing: {}".format(remove_entry.key)) self.remove(remove_entry.key) return req.Response(text='ok') def log_handler(self, req): if not req.json: print(f'request json is empty: {req.text}') return req.Response(text="Reuqest json is empty") log_entry = LogEntry(**req.json) print("writing: {} type: {} options: {}".format(log_entry.key, log_entry.type, log_entry.options)) data = deserialize(log_entry.data) self.log(log_entry.key, data, log_entry.type, LogOptions(*log_entry.options)) return req.Response(text='ok') def load(self, key, dtype): if dtype == 'read': abs_path = os.path.join(self.data_dir, key) try: with open(abs_path, 'rb') as f: return f.decode('utf-8') except FileNotFoundError as e: return None elif dtype == 'read_text': abs_path = os.path.join(self.data_dir, key) try: with open(abs_path, 'r') as f: return f.decode('utf-8') except FileNotFoundError as e: return None elif dtype == 'read_pkl': from ml_logger.helpers import load_from_pickle abs_path = os.path.join(self.data_dir, key) try: return list(load_from_pickle(abs_path)) except FileNotFoundError as e: return None elif dtype == 'read_np': import numpy abs_path = os.path.join(self.data_dir, key) try: return numpy.load(abs_path) except FileNotFoundError as e: return None elif dtype == 'read_image': raise NotImplemented('reading images is not implemented.') def remove(self, key): """ removes by key. :param key: the path from the logging directory. :return: None """ abs_path = os.path.join(self.data_dir, key) try: os.remove(abs_path) except FileNotFoundError as e: return None except OSError as e: import shutil shutil.rmtree(abs_path) def log(self, key, data, dtype, options: LogOptions = None): """ handler function for writing data to the server. Can be called directly. :param key: :param data: :param dtype: :param options: :return: """ # todo: overwrite mode is not tested and not in-use. write_mode = "w" if options and options.overwrite else "a" if dtype == "log": abs_path = os.path.join(self.data_dir, key) try: with open(abs_path, write_mode + 'b') as f: dill.dump(data, f) except FileNotFoundError: os.makedirs(os.path.dirname(abs_path)) with open(abs_path, write_mode + 'b') as f: dill.dump(data, f) if dtype == "byte": abs_path = os.path.join(self.data_dir, key) try: with open(abs_path, write_mode + 'b') as f: f.write(data) except FileNotFoundError: os.makedirs(os.path.dirname(abs_path)) with open(abs_path, write_mode + 'b') as f: f.write(data) elif dtype.startswith("text"): abs_path = os.path.join(self.data_dir, key) try: with open(abs_path, write_mode + "+") as f: f.write(data) except FileNotFoundError: os.makedirs(os.path.dirname(abs_path)) with open(abs_path, write_mode + "+") as f: f.write(data) elif dtype.startswith("yaml"): yaml = YAML() yaml.explict_start = True stream = StringIO() yaml.dump(data, stream) output = stream.getvalue() abs_path = os.path.join(self.data_dir, key) try: with open(abs_path, write_mode + "+") as f: if options.write_mode == 'key': d = yaml.load('\n'.join(f)) if d is not None: d.update(output) output = d f.write(output) except FileNotFoundError: os.makedirs(os.path.dirname(abs_path)) with open(abs_path, write_mode + "+") as f: if options.write_mode == 'key': d = yaml.load('\n'.join(f)) if d is not None: d.update(output) output = d f.write(output) elif dtype.startswith("image"): abs_path = os.path.join(self.data_dir, key) if "." not in key: abs_path = abs_path + ".png" from PIL import Image assert data.dtype in ALLOWED_TYPES, "image datatype must be one of {}".format(ALLOWED_TYPES) if len(data.shape) == 3 and data.shape[-1] == 1: data.resize(data.shape[:-1]) im = Image.fromarray(data) try: im.save(abs_path) except FileNotFoundError: os.makedirs(os.path.dirname(abs_path)) im.save(abs_path)
from japronto import Application from module.md_module import Document port = 7011 app = Application() async def query_func(request): mes = {"message": "success"} args = request.query form = request.match_dict r = Document.paginate(where=dict()) if r is None: mes['message'] = "Not Found!" else: mes['data'] = r resp = request.Response(text="ok") return resp app.router.add_route(pattern="/query", handler=query_func) if __name__ == "__main__": """ 和mongodb有兼容性问题,会报错: UserWarning: MongoClient opened before fork. Create MongoClient only after forking. """ app.run(host="0.0.0.0", port=port, debug=False, worker_num=2) pass
from japronto import Application def hello(request): return request.Response(text='Hello world!') app = Application() app.router.add_route('/', hello) app.run()
from japronto import Application def hello_world(request): return request.Response(text='Hello world') app = Application() app.router.add_route('/', hello_world) app.run(host='0.0.0.0', port=4000, worker_num=4)
from japronto import Application from ircalevents import get_day_events, get_month_events, get_year_events import json app = Application() async def get_events_year(request): result = await get_year_events(request.match_dict['year']) return request.Response(text=json.dumps(result, ensure_ascii=False), encoding='utf-8', mime_type='application/json') async def get_events_month(request): result = await get_month_events(request.match_dict['year'], request.match_dict['month']) return request.Response(text=json.dumps(result, ensure_ascii=False), encoding='utf-8', mime_type='application/json') async def get_events_day(request): result = await get_day_events(request.match_dict['year'], request.match_dict['month'], request.match_dict['day']) return request.Response(text=json.dumps(result, ensure_ascii=False), encoding='utf-8', mime_type='application/json') routes = app.router routes.add_route('/events/{year}', get_events_year, 'GET') routes.add_route('/events/{year}/{month}', get_events_month, 'GET') routes.add_route('/events/{year}/{month}/{day}', get_events_day, 'GET') app.run(host='127.0.0.1', port=5000)
#!/usr/bin/env python3 from japronto import Application def handle(request): try: a, b = request.query['a'], request.query['b'] except: return request.Response(text=str('')) return request.Response( text=str(float(a) / float(b))) if a and b else request.Response(text=str('')) app = Application() app.router.add_route('/', handle) app.run(debug=False, port=9099)
# A view can read HTML from a file def index(request): with open('index.html') as html_file: return request.Response(text=html_file.read(), mime_type='text/html') # A view could also return a raw HTML string def example(request): return request.Response(text='<h1>Some HTML!</h1>', mime_type='text/html') template = Template('<h1>Hello {{ name }}!</h1>') # A view could also return a rendered jinja2 template def jinja(request): return request.Response(text=template.render(name='World'), mime_type='text/html') # Create the japronto application app = Application() # Add routes to the app app.router.add_route('/', index) app.router.add_route('/example', example) app.router.add_route('/jinja2', jinja) # Start the server app.run(debug=True)
#!/usr/bin/env python3.5 # -*- coding: utf-8 -*- from japronto import Application def index(request): return request.Response(text='') def create_user(request): return request.Response(text='') def get_user(request): return request.Response(text=str(request.match_dict['id'])) app = Application() app.router.add_route('/', index) app.router.add_route('/user', create_user, 'POST') app.router.add_route('/user/{id}', get_user, 'GET') app.run(debug=False, port=3000)
from japronto import Application def ping(request): return request.Response(text='pong') app = Application() app.router.add_route('/', ping) app.run(debug=False)
#!/usr/bin/env python from japronto import Application def index(request): return request.Response(text='') def create_user(request): return request.Response(text='') def get_user(request): return request.Response(text=str(request.match_dict['id'])) app = Application() app.router.add_route('/', index) app.router.add_route('/user', create_user, 'POST') app.router.add_route('/user/{id}', get_user, 'GET') app.run(debug=False, port=3000)
@helper.simple_localizer def index(request, env): if request.method == 'POST': source = request.form.get('source', '') translated = helper.translate(source) helper.save_translation(source, translated) else: source = translated = '' template = env.get_template('index.html') return request.Response(text=template.render(source=source, translated=translated), mime_type='text/html') @helper.simple_localizer def words(request, env): with open('words.txt', 'r') as f: words = sorted(f.readlines()) template = env.get_template('vocab.html') return request.Response(text=template.render(words=words), mime_type='text/html') app = Application() app.router.add_route('/', index, methods=['GET', 'POST']) app.router.add_route('/vocab/', words, methods=['GET']) port = os.environ.get('PORT') or 8080 app.run(debug=True, port=int(port), reload=True)
# add docker to japronto app docker = Docker() app.extend_request(lambda x: docker, name='docker', property=True) async def check_first_init(): global FIRST_INIT print('check first init') data_source = with_sort(find_data_source()) if data_source is None: print('data source not found') FIRST_INIT = False return if get_size(DATA_SOURCE) == get_size(f"{ZPOOL_MOUNT}/{data_source.name}"): print('data source and stored data is correct') FIRST_INIT = True return app = Application() nc = NATS() app.loop.run_until_complete(connect_nats(app)) app.loop.run_until_complete(pull_image(message=True)) app.loop.run_until_complete(datanode_first_up()) app.loop.run_until_complete(check_first_init()) app.loop.run_until_complete(store_services()) app.loop.run_until_complete(connect_scheduler()) router = app.router router.add_route('/', list_services) app.run(debug=bool(int(os.getenv('DEBUG', 0))))
r.add_route('/state/assets/{ws}/{fn}/', get_state_from_assets, methods=['POST']) r.add_route('/envs/', env_create, methods=['POST']) r.add_route('/envs/', env_list_all, methods=['GET']) r.add_route('/envs/{instance_id}/reset/', env_reset, methods=['POST']) r.add_route('/envs/{instance_id}/step/', env_step, methods=['POST']) r.add_route('/envs/{instance_id}/state/', env_state, methods=['GET']) r.add_route('/envs/{instance_id}/info/', env_info, methods=['GET']) r.add_route('/envs/{instance_id}/close/', env_close, methods=['POST']) # TODO change if __name__ == '__main__': parser = argparse.ArgumentParser(description='Start a Gym HTTP API server') parser.add_argument('-l', '--listen', help='interface to listen to', default='127.0.0.1') parser.add_argument('-p', '--port', default=5000, type=int, help='port to bind to') args = parser.parse_args() print('Server starting at: ' + 'http://{}:{}'.format(args.listen, args.port)) app.run(host=args.listen, port=args.port, debug=True)
@route @jsonify def hello_world(request): # if you omit it though, the function name will be used return {"I'm served at": "/hello-world"} @route @jsonify def foo__bar(request): # double underscores map onto slashes return "I'm at /foo/bar" @route("/validation", "POST") @jsonify def basic_validation(request): # required integer query argument id = get_argument(request.query, "id", int) # optional `datetime` json argument with a default fallback at = get_argument(request.json, "at", datetime.fromisoformat, default=datetime.now()) return {"id": id, "at": at} app.run(port=8000, debug=True)
# coding: utf-8 from japronto import Application import Japronthost app = Application(); # Let Pronthost setup the routes ! Japronthost.setup_routes(".",app.router); # Runs the application app.run(debug=True);
def start(current_bot): global bot bot = current_bot server = Application() server.router.add_route('/', handle_all_activity) server.run(debug=True)
loginId = data["loginId"] password = data["password"] if loginId in authMap and authMap[loginId] == password: token = createToken() executor.submit(lambda: loginTokenProcess(token, loginId, loginToTokenMap, tokenToLoginIdMap)) return request.Response(json={ "token": token }) return request.Response(json='Rejected', code=401) async def api_call(request): global loginToTokenMap, tokenToLoginIdMap, authMap, executor token = request.json["token"] if not token in tokenToLoginIdMap: return request.Response(json=["TokenExpired", "TokenTampered", "InvalidToken"], code=401) loginId = tokenToLoginIdMap[token] if loginToTokenMap[loginId] != token: return request.Response(json=["MiddlemanPresent", "MightBeDesignError"], code=401) # Fit a reverse proxy newToken = createToken() executor.submit(lambda: loginTokenProcess(newToken, loginId, loginToTokenMap, tokenToLoginIdMap)) return request.Response(json={ "token": newToken, "result": "ABC" }) app = Application() app.router.add_route('/', hello) app.router.add_route('/login', login) app.router.add_route('/api_call', api_call) app.run(port=5000)
from celery_add import run_et from japronto import Application # This is a synchronous handler. def synchronous(request): return request.Response(json={'hello-everyone': run_et.delay().get()}) # This is an asynchronous handler, it spends most of the time in the event loop. # It wakes up every second 1 to print and finally returns after 3 seconds. # This does let other handlers to be executed in the same processes while # from the point of view of the client it took 3 seconds to complete. async def asynchronous(request): for i in range(1, 4): await asyncio.sleep(1) print(i, run_et.delay().get()) return request.Response(text='Done') app = Application() r = app.router r.add_route('/sync', synchronous) r.add_route('/async', asynchronous) # Finally start our server and handle requests until termination is # requested. Enabling debug lets you see request logs and stack traces. app.run(debug=True)
from japronto import Application async def minimal(request): return request.Response(json={'message': 'Hello, World!'}) async def parameter(request): return request.Response( json={'parameter': request.match_dict['parameter']}) app = Application() r = app.router r.add_route('/hello/minimal', minimal, method='GET') r.add_route('/hello/with/{parameter}', parameter, method='GET') if __name__ == '__main__': app.run(port=8000)
tmp = zh_dict.get(data['q']) if tmp != None: data = tmp del zh_dict[data['q']] break else: tmp = q_zh.get(False) #取数放到字典里 zh_dict[tmp['q']] = tmp await asyncio.sleep(1e-12) continue except: await asyncio.sleep(1e-12) continue res = data # print('return:',res) return request.Response(json={'res': res}) else: return request.Response(text='hello world!') router.add_route('/en2zh', en2zh, methods=['POST', 'GET']) router.add_route('/i2u/en2zh', en2zh, methods=['POST', 'GET']) router.add_route('/', en2zh, methods=['POST', 'GET']) # In[6]: app.run(port=5251, debug=True, worker_num=1) # In[ ]:
resp_types = {} try: # if client sends a JSON body, we use that to return as response resp_types['json'] = request.json except json.JSONDecodeError: resp_types['json'] = None finally: if not resp_types.get('json'): resp_types['text'] = 'ping pong' await asyncio.sleep((time_ms / 1000)) return request.Response(**resp_types) def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--port', type=int, default=8080) return parser.parse_args() if __name__ == '__main__': opts = parse_args() app = Application() app.router.add_route('/', hello) app.router.add_route('/delay/{time_ms}', handler_delay) app.add_error_handler(RouteNotFoundException, handler_err_not_found) app.run(debug=True, port=opts.port)
print(e) # remove all images with this tag for image in images: remove(image, tag) def remove(image, tag): untagged = False prune = True logger.info("Trying to delete %s:%s" % (image, tag)) try: cleaner = delete_docker_registry_image.RegistryCleaner(REGISTRY_DATA_DIR, dry_run) if untagged: cleaner.delete_untagged(image) else: if tag: cleaner.delete_repository_tag(image, tag) else: cleaner.delete_entire_repository(image) if prune: cleaner.prune() except delete_docker_registry_image.RegistryCleanerError as error: logger.fatal(error) app = Application() router = app.router router.add_route('/{project_namespace}/{project_name}/{tag}', batch_remove) router.add_route('/extra_path', single_remove) app.run(host='0.0.0.0', port=80, debug=True)
'interval', seconds=int(os.getenv('GBIR_SECONDS_TAGS', 11)), max_instances=10) scheduler.add_job(delete_tags, 'interval', seconds=int(os.getenv('GBIR_SECONDS_DELETE_TAGS', 60)), max_instances=1) scheduler.start() async def health_check(request): global QUEUE_PROJECTS global QUEUE_REGISTRY global QUEUE_TAGS return request.Response(json={ "QUEUE_PROJECTS": QUEUE_PROJECTS, "QUEUE_REGISTRY": QUEUE_REGISTRY, "QUEUE_TAGS": QUEUE_TAGS }, mime_type="application/json") app = Application() gl = gitlab.Gitlab(GBIR_URL, private_token=GBIR_TOKEN, api_version='4') app.loop.run_until_complete(get_projects()) app.loop.run_until_complete(connect_scheduler()) router = app.router router.add_route('/', health_check) app.run(port=80)
[ TRANSACTIONS.append(json.loads(transaction)) for transaction in redis_transactions._data_queue ] p = Process(name='serializer', target=serialize, args=(queue, )) p.start() print("Process SERIALIZER was created with PID: %s" % str(p.pid)) except Exception as e: if e.args[0] != "This event loop is already running": print("Can't connect to REDIS Server %s PORT %s" % (redis_host, redis_port)) print(e.args[0]) if __name__ == "__main__": asyncio.run(main()) rt.add_route('/', root) rt.add_route('/fill', fill) rt.add_route('/clear', clear) rt.add_route('/accounts', accounts) rt.add_route('/movements', movements) rt.add_route('/customers', customers) rt.add_route('/customers/register', customer_register) rt.add_route('/transactions', transactions) rt.add_route('/transfers', transfers) rt.add_route('/credit_cards', credit_cards) rt.add_route('/credit_cards/statement', credit_cards_statement) app.run(host="0.0.0.0", port=port)
from japronto import Application def hello(request): return request.Response(text='Hello world!') app = Application() r = app.router r.add_route('/', hello, method='GET') app.run()
payload = merge(lb_config, {"lbConfig": {"portRules": [{"protocol": os.getenv('RANCHER_LB_PROTOCOL', "http"), "type": os.getenv('RANCHER_LB_TYPE', "portRule"), "hostname": "{}-{}.{}".format(RLBU_ENVIRONMENT_SLUG, RLBU_PROJECT_PATH_SLUG, os.getenv('ENV_DOMAIN')), "sourcePort": int(os.getenv('EXTERNAL_PORT', 80)), "targetPort": int(os.getenv('INTERNAL_PORT', 8080)), "serviceId": request.match_dict['service_id']} ] } }) end_point = f"{V2_BETA}/projects/{os.getenv('RANCHER_ENVIRONMENT')}/loadbalancerservices/{load_balancer_id}" data = await put(end_point, payload) print(data['id']) hostname = "{}-{}.{}:{}".format( RLBU_ENVIRONMENT_SLUG, RLBU_PROJECT_PATH_SLUG, os.getenv('ENV_DOMAIN'), os.getenv('EXTERNAL_PORT', 80) ) print(f"update lb for {hostname}") return request.Response(text=hostname+"\n", mime_type="text/html") app = Application() app.router.add_route('/{service_id}', update_load_balancer_service) app.run(port=int(os.getenv('RLBU_PORT', 80)))
import sys from japronto import Application def index(request): return request.Response(text='') def create_user(request): return request.Response(text='') def get_user(request): return request.Response(text=str(request.match_dict['id'])) app = Application() app.router.add_route('/', index) app.router.add_route('/user', create_user, 'POST') app.router.add_route('/user/{id}', get_user, 'GET') app.run(host='0.0.0.0', worker_num=int(sys.argv[1]), port=3000)