コード例 #1
0
import re
import sqlite3
from contextlib import closing
from typing import Dict, List, Union

import responder
from requests_html import HTML, HTMLSession
from responder.models import Request, Response

api = responder.API(cors=True,
                    cors_params={'allow_origins': ['http://localhost:3001']})
session = HTMLSession()
DB_PATH = 'database.db'
DB_UPDATE_FLG = True


def get_docs_list_impl() -> List[Dict[str, Union[str, int]]]:
    # 話の一覧を取得する
    docs_list: List[Dict[str, Union[str, int]]] = []
    for year in range(2017, 2030):
        page = session.get(
            f'https://dc.watch.impress.co.jp/docs/comic/clinic/index{year}.html'
        )
        if not page.ok:
            break
        html: HTML = page.html
        temp_list: List[Dict[str, Union[str, int]]] = []
        for row in html.find('li.item.comic.clinic'):
            title = row.find('p.title > a', first=True).text
            doc_url: str = row.find('p.title > a', first=True).attrs['href']
            doc_id = re.sub(r'.*?(\d+)\.html', r'\1', doc_url)
コード例 #2
0
import responder

from kce.crawler import Fetcher
from kce.mail import sendMail

api = responder.API(version="0.1")
f = Fetcher()


@api.route("/")
def default(req, resp):
    resp.text = "OK"


@api.route("/latest/arxiv/{subject}")
def get_latest(req, resp, *, subject):
    papers = f.arxiv(subject)
    resp.media = papers


@api.route("/message")
class MessageService:
    async def on_post(self, req, resp):
        json = await req.media(format="json")

        if set(['email', 'name', 'message']).issubset(json.keys()):
            self.fromaddr = json['email']
            self.fromname = json['name']
            self.msg = json['message']

            if self.fromaddr and self.fromname and self.msg:
コード例 #3
0
ファイル: server.py プロジェクト: manzhikov/web-frameworks
import responder
from marshmallow import fields


class EmptyString(fields.Field):
    def encode(field, options):
        return ''


app = responder.API()


@app.route("/")
async def index(req, resp):
    resp.text = EmptyString()


@app.route('/user/{id}')
async def user_info(req, resp, *, id):
    resp.text = id


@app.route('/user')
async def user(req, resp):
    if req.method == 'post':
        resp.text = EmptyString()
コード例 #4
0
import responder
import requests
import asyncio

api = responder.API(title="Dinghy Ping", version="1.0", openapi="3.0.0", docs_route="/docs")

@api.route("/dinghy")
def dinghy_html(req, resp):
    resp.content = api.template('ping_input.html')

@api.route("/dinghy/ping/domains")
async def ping_multiple_domains(req, resp):
    """
    Async process to test multiple domains and return JSON with results
    Post request data example
    {
      "domains": [
        {
          "protocol": "https",
          "domain": "google.com"
        },
        {
          "protocol": "https",
          "domain": "microsoft.com"
        }
      ]
    }

    Return results
    {
      "domains": [
コード例 #5
0
# app.py

import os
import responder
from starlette.exceptions import HTTPException
from tortoise import Tortoise
from tortoise.exceptions import DoesNotExist, OperationalError
from models import User, Group, Person

api = responder.API(secret_key=os.urandom(64))
debug = True


@api.on_event("shutdown")
async def close_db_connection():
    await Tortoise.close_connections()


@api.on_event("startup")
async def init_db():
    """
    Initialize the database
    :return:
    """
    await Tortoise.init(db_url="sqlite://persons.db",
                        modules={"models": ["models"]})


@api.route("/api/v1.0/users")
async def get_users(req, resp):
    """
コード例 #6
0
ファイル: app.py プロジェクト: aaqaishtyaq/responder
import responder
import graphene

from flask import Flask

app = Flask(__name__)


@app.route("/")
def hello_world():
    return "Hello, World from flask!"


api = responder.API(enable_hsts=False)
api.mount("/hello", app)

import time


@api.route("/")
def hello(req, resp):
    # resp.status = responder.status.ok

    @api.background.task
    def sleep(s=10):
        # time.sleep(s)
        print("slept!")

    sleep()
    resp.content = api.template("test.html")
コード例 #7
0
import responder

cors_params = {
    'allow_origins': '*',
    'allow_methods': '*',
}

api = responder.API(cors=True, cors_params=cors_params)
コード例 #8
0
ファイル: app.py プロジェクト: hirohito-doi/oiraWaBeee
import responder

from models.date_selects import DateSelects

api = responder.API(static_dir='./static')

api.add_route("/", static=True)


@api.route("/api/date-select/{date}")
class DateSelectsAPI:
    def on_get(self, req, resp, *, date):
        model = DateSelects()
        dateSelects = model.get_all()

        resp.headers = {"Content-Type": "application/json; charset=utf-8"}
        resp.media = {"dateSelects": dateSelects}

    def on_post(self, req, resp, *, date):
        model = DateSelects()
        ret = model.add_data(date)

        # 返す値を設定する
        resp.headers = {"Content-Type": "application/json; charset=utf-8"}
        resp.media = {"status": ret}

    def on_delete(self, req, resp, *, date):
        model = DateSelects()
        ret = model.delete_data(date)

        # 返す値を設定する
コード例 #9
0
# set empty name list & empty encoding list
sample_names = []
sample_face_encoding_list = np.random.random(
    (len(sample_images), 128)).astype('float32')

# get sample encoding
for i, filename in enumerate(sample_images):
    face_encoding = cal_face_encoding(os.path.join(SAMPLE_IMAGE_DIR, filename))
    sample_face_encoding_list[i] = face_encoding
    sample_names.append(os.path.splitext(filename)[0])

print("setup samples done")

api = responder.API(
    openapi='3.0.0',  # OpenAPI version
    docs_route=
    '/docs',  # endpoint for interactive documentation by swagger UI. if None, this is not available.
)


@api.route("/")
async def view(req, resp):
    resp.media = {'success': True}


@api.route("/recognizer")
async def recognizer(req, resp):
    if req.method == 'get':
        # return form to upload an image you want to recognize
        # resp.status_code = 404
        resp.content = api.template('recognizer.html',
コード例 #10
0
ファイル: main.py プロジェクト: tokusumi/responder_tutorials
import responder
import time

api = responder.API(
    allowed_hosts=["*"],  # set allowed hosts
    secret_key='test',  # set secret_key
    # enable_hsts=True, # redirect http to https,
    # cors=True, # config for cors
    # cors_params={
    #     'allow_origins': ['https://example.org', 'https://www.example.org']
    # }
)

# define pre-response process
@api.route(before_request=True)
def prepare_response(req, resp):
    resp.headers["X-Pizza"] = "42"


# standard api
@api.route("/")
def hello_world(req, resp):
    resp.text = "hello world!"


# get key parameter
@api.route("/route/{who}")
def hello_world_key(req, resp, *args, who):
    resp.text = f"hello world, {who}!"

コード例 #11
0
import responder
from services.api.deadman_switch_api import DeadmanSwitchHealth

api = responder.API(
    title = "Deadman Switch Board",
    version = "0.1.0"
)

api.add_route("/health", DeadmanSwitchHealth)

if __name__ == '__main__':
    api.run()
コード例 #12
0
import os
import json

import responder
import numpy as np
from bpemb import BPEmb

env = os.environ
DEBUG = env['DEBUG'] in ['1', 'True', 'true']
LANG = env['LANG']
DIM = int(env['DIM'])
VS = int(env['VS'])

api = responder.API(debug=DEBUG)
bpemb = BPEmb(lang=LANG, dim=DIM, vs=VS)


def get_subwords(text):
    return bpemb.encode(text)


def get_emb(text):
    vectors = bpemb.embed(text)
    return np.mean(vectors, axis=0).tolist()


def get_subwords_and_emb(text):
    subwords = get_subwords(text)
    emb = get_emb(text)
    return dict(subwords=subwords, embedding=emb)
コード例 #13
0
import responder

api = responder.API(allowed_hosts=["*"], secret_key='test')


@api.route(before_request=True)
def pre_authentication(req, resp):
    """
    authentication: 
    the followings requests is valid,
    - static file
    - login view
    - correct session is equiped

    Others is redirected to login view 
    """
    # pass static file
    if req.url.path.startswith('/static/'):
        return

    # pass login
    elif req.url.path == '/login':
        return

    # pass having valid userid in session
    elif req.session.get('UserId', False) == 'user':
        return

    # login is necessary
    api.redirect(resp, f"/login?next='{req.url.path}'")
コード例 #14
0
import responder
import json

api = responder.API(templates_dir='./static')


#ホームにアクセスするとReactのviewが表示される
@api.route("/")
def index(req, resp):
    resp.html = api.template('index.html')


@api.route("/{file}/json")
def json_file(req, resp, *, file):
    with open('static/data/' + file + '.json', encoding="utf-8_sig") as f:
        data = json.load(f)

    resp.media = data


if __name__ == '__main__':
    api.run()
コード例 #15
0
import responder
from marshmallow import Schema, fields
import flask_sampler

openapi_params = {
    "title": "Sample API",
    "openapi": "3.0.0",
    "version": "1.0",
    "docs_route": "/docs"
}
api = responder.API(**openapi_params)


@api.route("/")
def index(req, resp):
    resp.text = "hello responder"


@api.schema("Echo")
class EchoSchema(Schema):
    message = fields.Str()


@api.route("/echo/{word}")
class Echo():
    """
    test docs
    ---
    get:
        description: echo back word.
        parameters:
コード例 #16
0
def api():
    return responder.API(debug=False, allowed_hosts=[";"])
コード例 #17
0
class UserInput(Model):
    word = CharField()
    frumfletta = ForeignKeyField(Frumfletta)
    count = IntegerField(default=0)

    class Meta:
        database = db


db.connect()
db.create_tables([UserInput, Frumfletta])

#beygingarlýsing
bin = BIN_Compressed()
# setting the header parameters in the constructor
api = responder.API(cors=True, cors_params={'allow_origins': ['*']})

API_URL = 'http://nidhoggur.rhi.hi.is/ordanet-api/api'
RANDOM_ENDPOINT = 'skyldheiti/handahof/'
RELATED_ENDPOINT = 'skyldheiti/'


@api.route('/skyldflettur')
def get_word(req, resp):
    while True:
        word = requests.get(
            f'{API_URL}/{RANDOM_ENDPOINT}').json()['results'][0]['frumfletta']
        if ' ' not in word:
            break
    payload = {'frumfletta': word}
    result_list = requests.get(f'{API_URL}/{RELATED_ENDPOINT}',
コード例 #18
0
# -*- coding: utf-8 -*-
"""Define the responder api instance."""

import os

import responder

package_dir = os.path.dirname(os.path.abspath(__file__))
static_dir = os.path.join(package_dir, "static")
template_dir = os.path.join(package_dir, "templates")

api = responder.API(
    static_dir=static_dir,
    templates_dir=template_dir,
    debug=True,
)
コード例 #19
0
from io import BytesIO
import responder
from fastai.vision import load_learner, open_image

MODEL_PATH = "./models"
MODEL_NAME = "bclass_v1_006.pkl"

print(f"Loading learner with model {MODEL_NAME}")
learner = load_learner(MODEL_PATH, MODEL_NAME)

api = responder.API(static_dir="./client/build", static_route="/")

api.add_route("/", static=True)


@api.route("/predict")
class Prediction:
    async def on_post(self, req, resp):
        formData = await req.media(format="files")
        img = open_image(BytesIO(formData['file']['content']))
        _, _, losses = learner.predict(img)
        resp.media = {
            "predictions":
            sorted(zip(learner.data.classes, map(float, losses)),
                   key=lambda p: p[1],
                   reverse=True)
        }


api.run()
コード例 #20
0
ファイル: controllers.py プロジェクト: moffy-Black/Blockchain
import responder
import os
from uuid import uuid4

from blockchain import Blockchain

node_identifier = str(uuid4()).replace('-', '')
blockchain = Blockchain()

api = responder.API(
  templates_dir='templates',
  static_dir='static',
  static_route='/static',
  secret_key=os.urandom(24)
)

class TransactionController:
  async def on_post(self, req, resp):
    data = await req.media()
    required = ['sender', 'recipient', 'amount']
    if not all(data.get('{}'.format(key)) for key in required):
      resp.status_code = 400
    index = blockchain.new_transaction(data.get('sender'),data.get('recipient'),data.get('amount'))
    response = {'message':f'トランザクションはブロック{index}に追加されました'}
    resp.media = response
    
class MineController:
  async def on_get(self, req, resp):
    last_block = blockchain.last_block
    last_proof = last_block['proof']
    proof = blockchain.proof_of_work(last_proof)
コード例 #21
0
ファイル: api.py プロジェクト: silvermullet/dinghy-ping
TAIL_LINES_DEFAULT = 100
LOGS_PREVIEW_LENGTH = 1000
TEMPLATE_DIR = 'dinghy_ping/views/templates/'
STATIC_DIR = 'dinghy_ping/views/static/'


def to_pretty_json(value):
    return json.dumps(value, sort_keys=True,
                      indent=4, separators=(',', ': '))


api = responder.API(
    title="Dinghy Ping",
    templates_dir=TEMPLATE_DIR,
    static_dir=STATIC_DIR,
    version="1.0",
    openapi="3.0.0",
    docs_route="/docs"
    )

api.jinja_env.filters['tojson_pretty'] = to_pretty_json

"""
For local mac docker image creation and testing, switch to host.docker.internal
"""
redis_host = os.getenv("REDIS_HOST", default="127.0.0.1")

"""
Dinghy Ping Host name used for web socket connection to collect logs
"""
dinghy_ping_host = os.getenv(
コード例 #22
0
from io import BytesIO

import responder
import aiohttp
from fastai import *
from fastai.vision import *

# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #

EXPORT_FILE_URL = 'https://www.dropbox.com/s/cot6bbu4w4dteei/trained_learner_allicroc.pkl?raw=1'
EXPORT_FILE_NAME = 'trained_learner_allicroc.pkl'

# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #

api = responder.API(cors=True)

path = Path(__file__).parent


# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
# First download the pickled model from url and then unpickle it:
async def download_file(url, dest):
    if dest.exists(): return
    async with aiohttp.ClientSession() as sess:
        async with sess.get(url) as resp:
            data = await resp.read()
            with open(dest, 'wb') as f:
                f.write(data)

コード例 #23
0
description = "knp-sandbox"
terms_of_service = "use your own risk"
contact = {
    "name": "@seiketkm",
    "url": "https://twitter.com/seiketkm",
}
license = {
    "name": "MIT",
    "url": "",
}

api = responder.API(title="knp-sandbox",
                    version="1.0",
                    openapi="3.0.2",
                    docs_route='/docs',
                    description=description,
                    terms_of_service=terms_of_service,
                    contact=contact,
                    license=license)


@api.schema("KnpRequest")
class KnpRequest(Schema):
    text = fields.Str(required=True,
                      default="望遠鏡で泳ぐ少女を見た。",
                      example="望遠鏡で泳ぐ少女を見た。")


@api.schema("KnpResult")
class KnpResult(Schema):
    all = fields.Str(
コード例 #24
0
ファイル: server.py プロジェクト: hack121/responder
import os
import responder

api = responder.API(enable_hsts=True)


@api.route("/")
def route(req, resp):
    resp.text = "hello, world!"


api.run(port=int(os.environ["PORT"]))
コード例 #25
0
ファイル: test_responder.py プロジェクト: gushil/responder
def api():
    return responder.API()
コード例 #26
0
import responder
import reprlib
import aioboto3
import asyncio
import twitter
import aiohttp
from typing import List
from dataclasses import dataclass
from face_detector import FaceDetector
from container import FileImage, FileImages

api = responder.API(cors=True,
                    cors_params={
                        'allow_origins': ['*'],
                        'allow_methods': ['*'],
                        'allow_headers': ['*'],
                    })


@api.route("/")
async def file_api(req, resp):

    data = await req.media(format='files')

    # データ生成
    file_images_list = []
    for key, value in data.items():
        file_image = FileImage(key, value['content'], {})
        file_images_list.append(file_image)
    file_images = FileImages(file_images_list)
コード例 #27
0
ファイル: www.py プロジェクト: kimsijin33/parcel-1
        "name": "Configure",
        "url": "/configure/",
        "id": "configure"
    },
    {
        "name": "Status",
        "url": "/status/",
        "id": "status"
    },
]

VALID_PAGES = [x['id'] for x in MENU] + ["provision"]

api = responder.API(
    static_dir="{}/static".format(ROOT),
    static_route="/static/{}".format(SNAP_REVISION),
    templates_dir="{}/templates".format(ROOT),
)


@api.route("/")
async def index(req, resp):
    if req.headers.get('TOKEN') == SECRET_TOKEN:
        resp.html = api.template('index.html',
                                 menu=MENU,
                                 current="/",
                                 page="index",
                                 static_hash=SNAP_REVISION)
    else:
        resp.text = "Error: You need to provide a correct TOKEN"
コード例 #28
0
ファイル: api.py プロジェクト: davidblurton/tala-wiktionary
import responder

from gql.schema import schema

api = responder.API(static_dir="build")

api.add_route("/graphql", schema)
api.add_route("/", static=True)

if __name__ == "__main__":
    api.run(address="0.0.0.0", port=5000)
コード例 #29
0
from logging import Logger
from settingstree import Settings
import responder
from starlette.websockets import WebSocketDisconnect, WebSocket, WebSocketState
from chain import ProcessingChain, WebFunctionDoesNotExistException
from json.decoder import JSONDecodeError
from threading import Thread, Lock
from collections import defaultdict
import sys
import asyncio

log = Logger(__name__)
settings = Settings()
responder_api = responder.API()

PlatformProcessingChain = ProcessingChain.get_platform_specific_chain()
processing_chain = PlatformProcessingChain(settings)

if not processing_chain:
    log.error('Your platform is currently not supported.')
    sys.exit(1)

# Load settings after chain initialized tree.
settings.load()


# TODO: move this somewhere else
class ProcessingThread(Thread):
    # TODO: move these to instance namespace?
    lock = Lock()
    ap_active = False
コード例 #30
0
def create_server(services):
    api = responder.API(cors=True)
    edge_resouce.add_route(api, services)

    return api