Beispiel #1
0
#!/usr/bin/env python
# Author: Ocean <*****@*****.**>

# Created Time: 日  3/ 5 17:47:22 2017
# coding=utf-8
## Last Modified : 一  3 06 11:20:37 2017

from japronto import Application


app = Application()
r = app.router


# Requests with the path set exactly to '/' and whatever method
# will be directed here.
def slash(request):
    return request.Response(text='Hello {} /!'.format(request.method))


r.add_route('/', slash)


# Requests with the path set exactly to '/love' and the method
# set exactly to 'GET' will be directed here.
def get_love(request):
    return request.Response(text='Got some love')

r.add_route('/love', get_love, 'GET')

# Requests with the path set exactly to '/methods' and the method
Beispiel #2
0
def basic_view(request):
    return json_response(request, {'hello':'Hello world!'})


def get_query_data(request):
    if request.body:
        if request.mime_type == "application/graphql":
            return {
                'query': request.body.decode("utf-8"),
                'operationName': request.query.get('operationName')
            }
        return get_json_body(request)

backend = GraphQLCachedBackend(GraphQLCoreBackend())

def graphql_view(request):
    data = get_query_data(request)
    query = data.get('query')
    operation_name = data.get('operationName')

    result = graphql(schema, query, backend=backend, operation_name=operation_name, validate=False)
    return json_response(request, result.to_dict())


if __name__ == '__main__':
    app = Application()
    app.router.add_route('/basic', basic_view)
    app.router.add_route('/graphql', graphql_view)
    app.run()
Beispiel #3
0
"""python japronto_app.py"""
from japronto import Application


def hello(request):
    return request.Response(text='Hello world!')


# 150000
app = Application()
app.router.add_route('/', hello)
app.run(debug=False, worker_num=4, port=8000)
Beispiel #4
0
import sys
from japronto import Application


async def hello(request):
    return request.Response(text='hello world')


class Application(Application):
    @property
    def _log_request(self):
        return False

    @_log_request.setter
    def _log_request(self, value):
        pass


port = int(sys.argv[1])

app = Application()
app.router.add_route('/', hello)
app.run(debug=False, port=port)
Beispiel #5
0
        pass
    conn = sqlite3.connect('example.sqlite')
    c = conn.cursor()
    c.execute('''
        CREATE TABLE product (
            product_id INTEGER PRIMARY KEY, 
            description TEXT)''')
    for product_id in range(1, NUMBER_OF_PRODUCTS + 1):
        description = ''.join(
            random.choice(string.ascii_letters + string.digits)
            for n in range(NUMBER_OF_RANDOM_LETTERS_IN_DESCRIPTION))
        c.execute('INSERT INTO product VALUES (?, ?)',
                  (product_id, description))
    conn.commit()


def params(request):
    product_id = request.match_dict['product_id']
    # actually discard `product_id` and use random
    product_id = random.randint(1, NUMBER_OF_PRODUCTS)
    c = conn.cursor()
    c.execute('SELECT description FROM product WHERE product_id=?',
              (product_id, ))
    description, = c.fetchone()
    return request.Response(text=description)


app = Application()
app.router.add_route('/{product_id}', params)
app.run(debug=False)
from japronto import Application
import time
# from time import time
import aiotarantool
import tarantool
from tarantool import const
import traceback
import asyncio
import uvloop

loop = uvloop.new_event_loop()
asyncio.set_event_loop(loop)
app = Application()
app._loop = loop


class TarantoolDriver():
    def __init__(self, host=None, port=None):
        if host and port:
            self.taran = aiotarantool.connect(str(host),
                                              int(port),
                                              user='******',
                                              password="******")
        else:
            self.taran = aiotarantool.connect("127.0.0.1",
                                              3311,
                                              user='******',
                                              password="******")

    async def close(self):
        print('Close {}'.format(str(self.__hash__)))
Beispiel #7
0
    loginId = data["loginId"]
    password = data["password"]
    if authenticate(loginId, password, authMap):
        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 next(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 })


app = Application()
app.router.add_route('/', hello)
app.router.add_route('/login', login)
app.router.add_route('/next', next)
app.run(port=8001)

Beispiel #8
0
# -*- coding: utf-8 -*-
from japronto import Application
from module.item_module import TempRecord


port = 7011
app = Application()


async def query_func(request):
    mes = {"message": "success"}
    args = request.query
    form = request.match_dict
    sn = form['sn'] if form.get('sn') else args.get("sn", "")
    f = {"sn": sn}
    r = TempRecord.find_one(filter_dict=f)
    if r is None:
        mes['message'] = "Not Found!"
    else:
        mes['result'] = str(r['_id'])
    resp = request.Response(text="ok")
    return resp



app.router.add_route(pattern="/query", handler=query_func)


if __name__ == "__main__":
    """
    和mongodb有兼容性问题,会报错:
Beispiel #9
0
from japronto import Application, RouteNotFoundException

from base.qiniu_cli import *
from helloword.ymlinks_basic import *
from helloword.ymlinks_body import *
from helloword.ymlinks_exception import *
from helloword.ymlinks_html import *
from helloword.ymlinks_req_extend import *
from helloword.ymlinks_todo import *
from wechat.wechat_gate import *

app = Application()
r = app.router
r.add_route('/', hello)
r.add_route('/sync', synchronous)
r.add_route('/async', asynchronous)
r.add_route('/love', get_love, 'GET')
r.add_route('/methods', methods, methods=['POST', 'DELETE'])
r.add_route('/params/{p1}/{p2}', params)
r.add_route('/basic', basic)
r.add_route('/body', body)
r.add_route('/misc', misc)
r.add_route('/text', text)
r.add_route('/encoding', encoding)
r.add_route('/mime', mime)
r.add_route('/qrcode/{p1}', generate_qrcode, method='GET')
r.add_route('/body', body)
r.add_route('/json', json)
r.add_route('/code', code)
r.add_route('/headers', headers)
r.add_route('/cookies', cookies)
import json

from japronto import Application


# Views handle logic, take request as a parameter and
# returns Response object back to the client
def hello(request):
    return request.Response(text=json.dumps({'foo': 'bar'}))


# The Application instance is a fundamental concept.
# It is a parent to all the resources and all the settings
# can be tweaked here.
app = Application()

# The Router instance lets you register your handlers and execute
# them depending on the url path and methods
app.router.add_route('/', hello)

# Finally start our server and handle requests until termination is
# requested. Enabling debug lets you see request logs and stack traces.
app.run(debug=False, port=8085)
Beispiel #11
0
                json["numberOfNearbyNeutralCreeps"],
                json["lowestEnemyCreepHealth"],
            )

            # Reward of choosing previous action
            reward = json["reward"]

            # Update the Deep Q Net with new state and the reward transitioning from
            # the previou state to this new state
            # Note: + 1 because Lua index starts at 1
            action = net.update(json["team"], reward, signal) + 1

            # Printing out some stats
            print(action, reward)
        except (JSONDecodeError, AttributeError) as e:
            print("Error")
            action = 1
        return req.Response(json={"action": action})
    return req.Response("hi")


def save(req):
    net.save()
    return req.Response("Saved")


app = Application()
app.router.add_route("/", main)
app.router.add_route("/save", save)
app.run(reload=True, debug=True)
Beispiel #12
0
    try:
        fp = 'files/' + request.query['fp']
        async with aiofiles.open(fp) as f:
            return request.Response(text=await f.read())
    except (FileNotFoundError, NotADirectoryError):
        return request.Response(text=f'No such file found: {fp}', code=404)

## Other useful stuff ##

async def b64(request):
    '''Encodes and decodes your given text'''
    mode = request.query.get('mode')
    message = request.query.get('message')
    if mode and message:
        if mode == 'encode':
            return request.Response(json={'response':base64.b64encode(message)}) 
        elif mode == 'decode':
            try:
                return request.Response(json={'response':base64.b64decode(message)}) 
            except:
                return request.Response(json={'response':'Invalid Base64 String to decode'}, status=400)
        else:
             return request.Response(json={'response':'Unknown mode'}, status=400)
    return request.Response(json={'response':'Invalid Call'}, status=400)

app = Application()
app.router.add_route('/', main)
app.router.add_route('/file', get_file)
app.router.add_route('/base64', b64) 
app.run(port=int(os.getenv('PORT')))
                rec_list = rec_list[:return_size]  #保留前n个

        except Exception as e:

            print(e)
            return_dict = {'status': 610, 'info': e, 'data': ['']}
            return request.Response(json=return_dict)

        if len(rec_list) > 0:

            for i in rec_list:
                pipe.execute_command('bf.add', user_id + '_bloom', i)

            tmp_result = pipe.execute()  # 给进布隆过滤器

            redis1.zremrangebyrank(user_id + md5_content, 0,
                                   return_size - 1)  # 已返回的就从redis表中移除

        #print(rec_list)

        return_dict = {'status': 200, 'info': 'success', 'data': rec_list}

        return request.Response(json=return_dict)

    return request.Response(text='穿山甲到底说了什么?')


app = Application()
app.router.add_route('/tuijian/v3.4', tuijian)
app.run(host='127.0.0.1', port=14593, debug=True)
Beispiel #14
0
#!/usr/bin/env python3
# -*- 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, host='0.0.0.0', port=3000)
Beispiel #15
0
# into 200 responses by the handlers registered later
def cat(request):
    raise KittyError()


def dog(request):
    raise DoggieError()


# This handler raises ZeroDivisionError which doesnt have an error
# handler registered so it will result in 500 Internal Server Error
def unhandled(request):
    1 / 0


app = Application()

r = app.router
r.add_route('/cat', cat)
r.add_route('/dog', dog)
r.add_route('/unhandled', unhandled)


# These two are handlers for `Kitty` and `DoggyError`s.
def handle_cat(request, exception):
    return request.Response(text='Just a kitty, ' + exception.greet)


def handle_dog(request, exception):
    return request.Response(text='Just a doggie, ' + exception.greet)
Beispiel #16
0
# into 200 responses by the handlers registered later
def cat(request):
    raise KittyError()


def dog(request):
    raise DoggieError()


# This handler raises ZeroDivisionError which doesn't have an error
# handler registered so it will result in 500 Internal Server Error
def unhandled(request):
    1 / 0


app = Application()

r = app.router
r.add_route('/cat', cat)
r.add_route('/dog', dog)
r.add_route('/unhandled', unhandled)


# These two are handlers for `Kitty` and `DoggyError`s.
def handle_cat(request, exception):
    return request.Response(text='Just a kitty, ' + exception.greet)


def handle_dog(request, exception):
    return request.Response(text='Just a doggie, ' + exception.greet)
Beispiel #17
0
# 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)

Beispiel #18
0
from japronto import Application
from routes import routes

app = Application()

routes.add_routes(app.router)

app.run(debug=True, port=9002)
Beispiel #19
0
import asyncio
import time

from japronto import Application


async def get_sync(request):
    time.sleep(5)
    return request.Response(text='OK')


async def get_async(request):
    await asyncio.sleep(5)
    return request.Response(text='OK')


app = Application()
app.router.add_route('/sync', get_sync)
app.router.add_route('/async', get_async)
app.run(port=5000)
Beispiel #20
0
                    if i not in service_to_remove:
                        service_to_remove.append(i)
        except Exception as e:
            print(e)
    try:
        for stack in stack_to_remove:
            print(f"remove {stack.name}")
            stack.remove()
        for service in service_to_remove:
            print(f"remove {service.stack().name}/{service.name}")
            service.remove()
    except Exception as e:
        print(e)

async def connect_scheduler():
    scheduler = AsyncIOScheduler(timezone="UTC")
    scheduler.add_job(get_project_and_stacks, 'interval', seconds=int(os.getenv('get_project_and_stacks', 1800)))
    scheduler.add_job(find_old_containers, 'interval', seconds=int(os.getenv('find_old_containers', 1200)))
    scheduler.add_job(clean_old_ss, 'interval', seconds=int(os.getenv('remove_old_ss', 600)))
    scheduler.start()


app = Application()
app.loop.run_until_complete(get_project_and_stacks())
app.loop.run_until_complete(find_old_containers())
app.loop.run_until_complete(clean_old_ss())
app.loop.run_until_complete(connect_scheduler())
router = app.router
router.add_route('/', index)
app.run(debug=bool(int(os.getenv('DEBUG', 0))))
Beispiel #21
0
DB_FILE = os.path.abspath(
    os.path.join(os.path.dirname(__file__), 'todo.sqlite'))
db_connect = partial(sqlite3.connect, DB_FILE)


def maybe_create_schema():
    db = db_connect()
    db.execute("""
        CREATE TABLE IF NOT EXISTS todos
        (id INTEGER PRIMARY KEY, todo TEXT)""")
    db.close()


maybe_create_schema()
app = Application()


def cursor(request):
    def done_cb(request):
        request.extra['conn'].close()

    if 'conn' not in request.extra:
        request.extra['conn'] = db_connect()
        request.add_done_callback(done_cb)

    return request.extra['conn'].cursor()


app.extend_request(cursor, property=True)
router = app.router
Beispiel #22
0
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)
Beispiel #23
0
    request.add_done_callback(cb)

    return request.Response(text='cb')


# This is a body for reversed_agent property
def reversed_agent(request):
    return request.headers['User-Agent'][::-1]


# This is a body for host_startswith method
# Custom methods and properties always accept request
# object.
def host_startswith(request, prefix):
    return request.headers['Host'].startswith(prefix)

app = Application()
# Finally register out custom property and method
# By default the names are taken from function names
# unelss you provide `name` keyword parameter.
app.extend_request(reversed_agent, property=True)
app.extend_request(host_startswith)

r = app.router
r.add_route('/', extended_hello)
r.add_route('/callback', with_callback)


app.run()
import sys
from multiprocessing import cpu_count
from japronto import Application


def naked(request):
    return request.Response(b'Naked!')


app = Application()
app.router.add_route('/', naked, method='GET')
app.run(debug=False)

if __name__ == '__main__':
    app.run(host=sys.argv[1],
            workers=cpu_count(),
            debug=False,
            port=int(sys.argv[2]))
Beispiel #25
0
    this_catalog = REGISTRY.query(f"{registry_url}/v2/_catalog",
                                  'get')['repositories']
    if len(this_catalog) != len(CATALOG):
        print(f"Found {len(this_catalog)} repositories")
    CATALOG = this_catalog


async def connect_scheduler():
    scheduler = AsyncIOScheduler(timezone="UTC")
    scheduler.add_job(get_catalog,
                      'interval',
                      seconds=int(os.getenv('DRIC_SECONDS_CATALOG', 300)),
                      max_instances=1)
    scheduler.start()


async def index(request):
    global CATALOG
    return request.Response(json=CATALOG)


app = Application()
app.extend_request(lambda x: REGISTRY, name='registry', property=True)
app.loop.run_until_complete(get_catalog(first_load=True))
app.loop.run_until_complete(connect_scheduler())
router = app.router
router.add_route('/{project_namespace}/{project_name}/{tag}', batch_remove)
router.add_route('/extra_path', single_remove)
router.add_route('/', index)
app.run(host='0.0.0.0', port=80, debug=True)
Beispiel #26
0
def start(current_bot):
    global bot
    bot = current_bot
    server = Application()
    server.router.add_route('/', handle_all_activity)
    server.run(debug=True)
Beispiel #27
0
    return plyvel.DB(path, create_if_missing=True)


def env(request):
    result =  "remote_addr: " + request.remote_addr + "\n" + \
              "hostname: " + request.hostname + "\n" + \
              "port: " + str(request.port) + "\n\n"
    if request.headers:
        for name, value in request.headers.items():
            result += "  {0}: {1}\n".format(name, value)
    return request.Response(text=result)


def db(request):
    result = "open"
    if DB.closed:
        result = "closed"
    else:
        DB.close()
        result = "close the DB"
    return request.Response(text=result)


DB = open_leveldb(leveldb_path)

app = Application()
app.router.add_route("/env", env)
app.router.add_route("/db", db)

app.run(debug=True, host=host_name, port=port_number)
Beispiel #28
0
import json
from app.utils import rule_util
import traceback


from app.config.logging_config import config as log_config_dict

# Setup logging
logging.config.dictConfig(log_config_dict)

info_logger = logging.getLogger('info_logger')
debug_logger = logging.getLogger('debug_logger')
error_logger = logging.getLogger('error_logger')


application = Application()


def ping(request):
    info_logger.info('/ping')
    return request.Response(code=200,
                            text=json.dumps({'message': 'Hey, I\'m running'}),
                            mime_type='application/json')


def get_rule_type(request):
    try:
        match_dict = request.match_dict
        info_logger.info('REQ: {}'.format(str(match_dict)))
        res = rule_util.get_rule_type(match_dict)
        info_logger.info('RES: {}'.format(str(res)))
Beispiel #29
0
def init(loop_param=None, port_param=None):
    """Init Janpronto server in like-oop style."""
    global loop, port, app
    loop = loop_param
    port = port_param
    app = Application()
#!/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)
Beispiel #31
0
from japronto import Application


def ping(request):
    return request.Response(json={'message': 'pong'})


app = Application()
app.router.add_route('/', ping)
app.run(debug=False, worker_num=8)
Beispiel #32
0
        await mongoHandler.set_db_and_collection('beepaste', 'texts')
        inited = 1

    body = request.json
    ret = await mongoHandler.insert(body)
    return request.Response(json={'id': str(ret.inserted_id)})


async def fetch(request):
    global inited
    if not inited:
        await mongoHandler.get_connection()
        await mongoHandler.set_db_and_collection('beepaste', 'texts')
        inited = 1

    body = request.json['id']
    ret = await mongoHandler.findById(body)
    return request.Response(json={
        'id': str(ret['_id']),
        'text': str(ret['text'])
    })


app = Application()
r = app.router

r.add_route('/save', save, methods=['POST'])
r.add_route('/fetch', fetch, methods=['POST'])

app.run(port=8080)
Beispiel #33
0

async def connect_scheduler():
    scheduler = AsyncIOScheduler(timezone="UTC")
    scheduler.add_job(add_registry_path,
                      CronTrigger.from_crontab(
                          os.getenv('DRS3GC_CRON_PATH', '0 0 * * 0')),
                      max_instances=1)
    scheduler.add_job(cleanup_tag,
                      'interval',
                      seconds=int(os.getenv('DRS3GC_SECONDS_CLEANUP', 5)),
                      max_instances=10)
    scheduler.add_job(scan_bucket,
                      'interval',
                      seconds=int(os.getenv('DRS3GC_SECONDS_SCAN', 1)),
                      max_instances=10)
    scheduler.start()


async def index(request):
    global REGISTRY_LATEST
    return request.Response(json=REGISTRY_LATEST)


app = Application()
app.loop.run_until_complete(scan_bucket())
app.loop.run_until_complete(connect_scheduler())
router = app.router
router.add_route('/', index)
app.run(host='0.0.0.0', port=80, debug=True)
#!/usr/bin/env python3
# -*- 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)
Beispiel #35
0
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()
Beispiel #36
0
    request.add_done_callback(cb)

    return request.Response(text='cb')


# This is a body for reversed_agent property
def reversed_agent(request):
    return request.headers['User-Agent'][::-1]


# This is a body for host_startswith method
# Custom methods and properties always accept request
# object.
def host_startswith(request, prefix):
    return request.headers['Host'].startswith(prefix)


app = Application()
# Finally register the  custom property and method
# By default the names are taken from function names
# unelss you provide `name` keyword parameter.
app.extend_request(reversed_agent, property=True)
app.extend_request(host_startswith)

r = app.router
r.add_route('/', extended_hello)
r.add_route('/callback', with_callback)


app.run()