예제 #1
0
import falcon

from signup import signup
from login import login
from activeprj import gPrj

from falcon.http_status import HTTPStatus


#gunicorn -b 0.0.0.0:5000 auth_signup:api --reload &
class HandleCORS(object):
    def process_request(self, req, resp):
        resp.set_header('Access-Control-Allow-Origin', '*')
        resp.set_header('Access-Control-Allow-Methods', '*')
        resp.set_header('Access-Control-Allow-Headers', '*')
        resp.set_header('Access-Control-Max-Age', 1728000)  # 20 days
        if req.method == 'OPTIONS':
            raise HTTPStatus(falcon.HTTP_200, body='\n')


#wsgi_app = api = falcon.API(middleware=[HandleCORS() ])
api = falcon.API(middleware=[HandleCORS()])

signup = signup()
login = login()
gprj = gPrj()

api.add_route('/api/v1/signup', signup)
api.add_route('/api/v1/login', login)
api.add_route('/api/v1/getAllProj', gprj)
예제 #2
0
def create_api(
    cfg: attrdict.AttrDict,
    schema: graphene.Schema,
    scoped_session: sqlalchemy.orm.scoped_session,
    logger_level: str,
):
    """Creates a Falcon API and adds resources for the GraphQL endpoint.

    Args:
        cfg (attrdict.Attrdict): The application configuration loaded with the
            methods under the `config.py` module.
        schema (graphene.Schema): An instance of the Graphene schema to expose
            via the GraphQL endpoint.
        scoped_session (sqlalchemy.orm.scoped_session): A SQLAlchemy
            scoped-session that will be used to perform the interaction with
            the SQL database.
        logger_level (str): The logger level to be set in the Falcon resource
            classes.

    Returns:
        falcon.api.API: The instantiate Falcon API.
    """

    # Create logger.
    logger = create_logger(
        logger_name=__name__,
        logger_level=logger_level
    )

    # Create the API.
    api = falcon.API(
        middleware=[
            # Instantiate and add the CORS middleware.
            MiddlewareCors(logger_level=logger_level),
            # Instantiate and add the Auth0 authentication middleware.
            MiddlewareAuth0(
                auth0_domain=cfg.auth0.domain,
                auth0_audience=cfg.auth0.audience,
                auth0_jwks_url=cfg.auth0.jwks_url,
                logger_level=logger_level,
            ),
        ],
    )

    msg_fmt = "Initializing API resources."
    logger.info(msg_fmt)

    # Add the GraphQL route.
    api.add_route(
        uri_template="/graphql",
        resource=ResourceGraphQlSqlAlchemy(
            cfg=cfg,
            schema=schema,
            scoped_session=scoped_session,
        )
    )

    msg_fmt = "API initialization complete."
    logger.info(msg_fmt)

    return api
예제 #3
0
from wsgiref import simple_server

import falcon

from . import handlers
from .middleware import ResponseLoggerMiddleware

app = falcon.API(middleware=[ResponseLoggerMiddleware()])
"""
Messages URL"s
"""
app.add_route("/messages/{message_id:int}", handlers.MessageDetailResource())
"""
Thread URL"s
"""
app.add_route("/threads", handlers.ThreadListResource())
app.add_route("/threads/{thread_id:int}", handlers.ThreadDetailResource())
app.add_route("/threads/users/{user_id:int}",
              handlers.ThreadUserListResource())
app.add_route("/threads/{thread_id:int}/messages",
              handlers.ThreadMessageListResource())
"""
Alert URL's
"""
app.add_route("/alerts/{user_id:int}", handlers.AlertsResource())
"""
Health Check
"""
app.add_route("/shc", handlers.HealthCheckResource())

if __name__ == "__main__":
예제 #4
0
def main():
    APP = falcon.API()
    APP.add_route('/nlp', GcloudNlpResource())

    httpd = simple_server.make_server('0.0.0.0', 8000, APP)
    httpd.serve_forever()
예제 #5
0
            print(config)
        else:
            resp.status = '401'

    def on_delete(req, resp):
        if req.context['auth']:
            challenge = req.get_param('challenge')
            competition = req.get_param('competition')
            if not challenge or not competition:
                resp.status = '400'
                return
            problemdir = os.path.abspath(
                os.path.join(config['root'], competition, challenge))
        else:
            resp.status = '401'


class AuthMiddleware(object):
    def __init__(self, secret):
        self.secret = secret

    def process_resource(self, req, resp, resource, params):
        req.context['auth'] = req.get_header('Authorization') == self.secret


app = falcon.API(middleware=[
    AuthMiddleware(os.environ['SHELL_DEPLOY_SECRET']),
    MultipartMiddleware()
])
app.add_route('/challenge', ChallengeLoader)
예제 #6
0
def build_application(runner_fn=None):
    application = falcon.API()
    runner = build_runner() if runner_fn is None else runner_fn()
    add_api_routes(application, runner)
    return application
예제 #7
0
            # on ne retourne les coordonnées Lambert que si on est en zone Lambert93
            if y > -357823.2365 and x > 6037008.6939 and y < 1313632.3628 and x< 7230727.3772:
                data['x'] = int(x)
                data['y'] = int(y)

            geojson = {"type":"Feature",
                "properties":data,
                "params":geonym.getParams(),
                "geocode":geo,
                "reverse":rev,
                "geometry":{"type":"Polygon","coordinates":[[[data['west'],data['south']],[data['east'],data['south']],[data['east'],data['north']],[data['west'],data['north']],[data['west'],data['south']]]]}}
            resp.body = json.dumps(geojson, sort_keys=True, indent=4, separators=(',', ': '))
            resp.set_header('Content-type','application/json')
        else:
            resp.status = falcon.HTTP_400
            resp.set_header('Content-type','text/html')
            resp.body = "README dispo sur <a href='https://github.com/geonym/geonymapi'>https://github.com/geonym/geonymapi</a>"

    def on_get(self, req, resp, query=None):
        self.getGeonym(req, resp, query);


# Falcon.API instances are callable WSGI apps.
app = falcon.API(middleware=[HeaderMiddleware()])

# Resources are represented by long-lived class instances
g = GeonymResource()

# things will handle all requests to the matching URL path
app.add_route('/{query}', g)
예제 #8
0
from app.resources.harvester import PolkascanStartHarvesterResource, PolkascanStopHarvesterResource, \
    PolkascanStatusHarvesterResource, PolkascanProcessBlockResource, \
    PolkaScanCheckHarvesterTaskResource, SequenceBlockResource, PolkascanBacktrackingResource, PolkascanAccountBalance, \
    PolkascanSyncAccountId
from app.resources.tools import ExtractMetadataResource, ExtractExtrinsicsResource, \
    HealthCheckResource, ExtractEventsResource

# Database connection
engine = create_engine(DB_CONNECTION,
                       echo=DEBUG,
                       isolation_level="READ_UNCOMMITTED")
session_factory = sessionmaker(bind=engine, autoflush=False, autocommit=False)

# Define application
app = falcon.API(middleware=[
    ContextMiddleware(),
    SQLAlchemySessionManager(session_factory)
])

# Application routes
app.add_route('/healthcheck', HealthCheckResource())

app.add_route('/start', PolkascanStartHarvesterResource())
app.add_route('/stop', PolkascanStopHarvesterResource())
app.add_route('/status', PolkascanStatusHarvesterResource())
app.add_route('/process', PolkascanProcessBlockResource())
app.add_route('/sequence', SequenceBlockResource())
app.add_route('/task/result/{task_id}', PolkaScanCheckHarvesterTaskResource())

app.add_route('/tools/metadata/extract', ExtractMetadataResource())
app.add_route('/tools/extrinsics/extract', ExtractExtrinsicsResource())
app.add_route('/tools/events/extract', ExtractEventsResource())
예제 #9
0
def _build_app():
    import falcon

    app = falcon.API()

    return app
예제 #10
0
def client(resource):
    app = falcon.API()
    app.add_route('/', resource)
    return testing.TestClient(app)
예제 #11
0
def client():
    api = falcon.API()
    api.add_route('/api/parse/train', TrainParseResource())
    client = falcon.testing.TestClient(api)
    return client
예제 #12
0
파일: webhook.py 프로젝트: ulskusqt/Sender
 def get_webhook_app(self):
     app = falcon.API()
     self.on_get = self._on_get
     self.on_post = self._on_post
     app.add_route("/", self)
     return app
예제 #13
0
import falcon
import resources

from falcon_cors import CORS

# cors = CORS(allow_origins_list=['http://localhost:8100', 'http://192.168.0.202:8100'],
#             allow_methods_list=['POST', 'PUT', 'GET'], allow_headers_list=['Content-Type'])
cors = CORS(allow_all_origins=True,
            allow_all_methods=True,
            allow_all_headers=True)

api = application = falcon.API(middleware=[cors.middleware])

resources.add_routes(api)
예제 #14
0
def create_app():
    app = falcon.API()

    app.add_route('/', index)
    app.add_route('/storagerooms', storagerooms)
    return app
예제 #15
0
                question = formatter.format_question(insight, lang)
                questions.append(question.serialize())

            response['questions'] = questions
            response['status'] = "found"

        resp.media = response


cors = CORS(allow_all_origins=True,
            allow_all_headers=True,
            allow_all_methods=True)

api = falcon.API(middleware=[
    cors.middleware,
    MultipartMiddleware(),
    DBConnectionMiddleware()
])
# Parse form parameters
api.req_options.auto_parse_form_urlencoded = True
api.add_route('/api/v1/insights/{barcode}', ProductInsightResource())
api.add_route('/api/v1/insights/random', RandomInsightResource())
api.add_route('/api/v1/insights/annotate', AnnotateInsightResource())
api.add_route('/api/v1/insights/import', InsightImporterResource())
api.add_route('/api/v1/predict/ingredients/spellcheck',
              IngredientSpellcheckResource())
api.add_route('/api/v1/products/dataset', UpdateDatasetResource())
api.add_route('/api/v1/webhook/product', WebhookProductResource())
api.add_route('/api/v1/images/import', ImageImporterResource())
api.add_route('/api/v1/images/predict', ImagePredictorResource())
api.add_route('/api/v1/questions/{barcode}', ProductQuestionsResource())
예제 #16
0
        try:
            template = self.jinja_env.get_template(template_name)
        except TemplateNotFound:
            raise falcon.HTTPNotFound(
                title='Template not found',
                description='No such template: "{}"'.format(template_name)
            )
        try:
            variables = json.loads(req.params.get('content', '{}'))
        except json.JSONDecodeError:
            raise falcon.HTTPBadRequest(
                title='Failed to decode "content" parameter',
                description='Value of query parameter "content" is not JSON deserializable'
            )
        resp.body = template.render(**variables)
        resp.status = falcon.HTTP_OK


app = falcon.API(middleware=JSONParamConsolidationMiddleware())
app.add_route('/{template_name}', RenderTemplateResponder())


if __name__ == '__main__':
    httpd = simple_server.make_server(host='localhost', port=8000, app=app)
    print('Running on http://localhost:8000')
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        print('Shutting down...')
        httpd.shutdown()
예제 #17
0
def client_predictv1():
    api = falcon.API(middleware=TestMiddleware())
    api.add_route('/api/parse/v1/predict', PredictionResource_V1())
    client = falcon.testing.TestClient(api)
    return client
예제 #18
0
        base = base64.b64decode(encoded)
        
        return base

    def get_face_encondings(self, image, req):
        unknown_image = face_recognition.load_image_file(BytesIO(image))
        unknown_encoding = face_recognition.face_encodings(unknown_image)

        return unknown_encoding

    def compare_faces(self, unknown_encoding, req):
        comp = face_recognition.compare_faces([biden_encoding], unknown_encoding[0])
        return comp

    def save_to_storage(self, image, filename, req):
        """
        Send binary file to storage.
        """
        storage.upload_fileobj(BytesIO(image), filename)


app = falcon.API(middleware=[
    MatchResultLoggingMiddleware(),
])

resources = ImageDetectionResource()
app.add_route('/', resources)

if __name__ == '__main__':
    run_simple('0.0.0.0', 5000, app, use_reloader=True, use_debugger=True)
예제 #19
0
def set_access_control(req, resp, params):
    resp.set_header('Access-Control-Allow-Origin', '*')
    resp.set_header('Access-Control-Allow-Headers',
                    'Snap-Server-Authorization, Authorization')
    resp.set_header('Access-Control-Allow-Methods', 'GET, POST')
    resp.set_header('Allow', 'GET, POST')


sql_engine = sqlengine.create_engine('sqlite:///snap.sqlite', echo=False)
sql_connection = sql_engine.connect()
Session = sessionmaker(bind=sql_engine)

Base.metadata.create_all(sql_engine)

app = falcon.API(before=[set_access_control],
                 media_type='application/xml; charset=utf-8')

app.add_sink(raise_unknown_url)
app.add_route('/', NoMethod())
app.add_route('/{method}', UnknownMethod())

app.add_route('/addStudent', AddStudent())
app.add_route('/addTeacher', AddTeacher())
app.add_route('/changePassword', ChangePassword())
app.add_route('/createAssignment', CreateAssignment())
app.add_route('/createCourse', CreateCourse())
app.add_route('/createProject', CreateProject())
app.add_route('/createUser', CreateUser())
app.add_route('/enroll', Enroll())
app.add_route('/getProjectByName', GetProjectByName())
app.add_route('/getRevision', GetRevision())
예제 #20
0
import falcon
from falcon_cors import CORS
from project.controller import *
from project.model.models import *

cors = CORS(
    # allow_origins_list=[

    # ],
    allow_all_headers=True,
    allow_all_origins=True,
    allow_methods_list=['GET', 'POST', 'OPTIONS'])
app = falcon.API(middleware=[cors.middleware])
# app = falcon.API()

# User APIs
# Branch
app.add_route("/branch/auth/sign-up", BranchSignup())
app.add_route("/branch/auth/login", BranchLogin())
app.add_route("/branch/customer/add", AddCustomer())
app.add_route("/branch/customer/list", CustomerListing())

# Branch
app.add_route("/head/auth/sign-up", HeadSignup())
app.add_route("/head/auth/login", HeadLogin())
예제 #21
0
import falcon

from upskill.resources.file import FileResource
from upskill.resources.files_summary import FilesSummaryResource
from upskill.resources.healthcheck import HealthcheckResource
from upskill.auth import AuthorizationMiddleware

middlewares = [AuthorizationMiddleware()]

api = falcon.API(middleware=middlewares)

api.add_route('/', FilesSummaryResource())
api.add_route('/files', FilesSummaryResource())
api.add_route('/files/{filename}', FileResource())

api.add_route('/healthcheck', HealthcheckResource())
예제 #22
0
import json

import falcon

api = application = falcon.API()


class Resource(object):
    def on_get(self, req, resp):
        resp.body = json.dumps({"msg": "falcon!"})
        resp.status = falcon.HTTP_200


resource = Resource()
api.add_route('/', resource)
예제 #23
0
파일: app.py 프로젝트: huxiaoxidian/myems
########################################################################################################################
# BEGIN imports for Enterprise Version
########################################################################################################################

########################################################################################################################
# END imports for Enterprise Version
########################################################################################################################

# https://github.com/lwcolton/falcon-cors
# https://github.com/yohanboniface/falcon-multipart
cors = CORS(allow_all_origins=True,
            allow_credentials_all_origins=True,
            allow_all_headers=True,
            allow_all_methods=True)
api = falcon.API(middleware=[cors.middleware, MultipartMiddleware()])

########################################################################################################################
# Routes for System Configuration
########################################################################################################################

api.add_route('/combinedequipments',
              combinedequipment.CombinedEquipmentCollection())
api.add_route('/combinedequipments/{id_}',
              combinedequipment.CombinedEquipmentItem())
api.add_route('/combinedequipments/{id_}/equipments',
              combinedequipment.CombinedEquipmentEquipmentCollection())
api.add_route('/combinedequipments/{id_}/equipments/{eid}',
              combinedequipment.CombinedEquipmentEquipmentItem())
api.add_route('/combinedequipments/{id_}/meters',
              combinedequipment.CombinedEquipmentMeterCollection())
예제 #24
0
        return jsonify(result)

    def _process(self, img, resp):
        fname = img.filename

        with open(fname, 'wb') as out:
            out.write(img.file.read())
        resp.body = self._run_model(fname)
        resp.status = falcon.HTTP_200
        os.remove(fname)

    def on_post(self, req, resp):
        img = req.get_param('image')
        if img is None:
            resp.body = jsonify({'success': False, 'error': 'Image not found'})
            return
        try:
            self._process(img, resp)
        except Exception:
            ex_type, ex_value, ex_traceback = sys.exc_info()
            resp.body = jsonify({'success': False, 'error': f'{ex_type.__name__}: {ex_value}'})


tasks = set(os.environ.get('CEEVEE_TASKS', 'dummy').split(','))
models = {task: MODELS[task]() for task in tasks}
app = falcon.API(middleware=[MultipartMiddleware()])

for task, model in models.items():
    app.add_route(f'/{task}', BaselineServer(model))

예제 #25
0
class UIResource:
    def on_get(self, req, res):
        res.content_type = 'text/html'
        res.body = html_body


class SynthesisResource:
    def on_get(self, req, res):
        if not req.params.get('text'):
            raise falcon.HTTPBadRequest()
        res.data = synthesizer.synthesize(req.params.get('text'))
        res.content_type = 'audio/wav'


synthesizer = Synthesizer()
api = falcon.API()
api.add_route('/synthesize', SynthesisResource())
api.add_route('/', UIResource())

if __name__ == '__main__':
    from wsgiref import simple_server
    parser = argparse.ArgumentParser()
    parser.add_argument('--checkpoint',
                        required=True,
                        help='Full path to model checkpoint')
    parser.add_argument('--port', type=int, default=4000)
    #Colab laboratory 사용 도중 9000포트를 사용하면 Address already in use Error 발생
    #해결 방법 : !lsof -i :<port> 명령어 입력을 통해 사용중이지 않은 포트 번호를 찾는다. 그 번호로 바꿨다.
    #9000포트 -> 4000포트
    parser.add_argument(
        '--hparams',
예제 #26
0
import falcon_jsonify
import json
import resources.hero as hero
import resources.guild as guild
import resources.search as search
import resources.pigeoncoop as pcoop
import resources.pigeon as pigeon
import resources.userAuth as auth
from falcon_cors import CORS

from pymongo import MongoClient

cors = CORS(allow_all_origins=True)

application = falcon.API(middleware=[
    falcon_jsonify.Middleware(help_messages=True), cors.middleware
])

#TODO Edit <USR> and <PASSWORD> before deploy
#TODO Edit Change TestLibrary to GreatLibrary before deploy
DB_REF = MongoClient(
    "mongodb://<USR>:<PASSWORD>@cluster0-shard-00-00-ygomb.mongodb.net:27017,cluster0-shard-00-01-ygomb.mongodb.net:27017,cluster0-shard-00-02-ygomb.mongodb.net:27017/TestLibrary?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin"
).GreatLibrary

#image_collection = images.Collection(storage_path)
#image = images.Item(storage_path)

#application.add_route('/images', image_collection)
#application.add_route('/images/{name}', image)

예제 #27
0
파일: wsgiapp.py 프로젝트: jgehrcke/bouncer
        auth.login_provider_item_builders.append(builder)

    if hasattr(mod, 'get_module_middlewares'):
        for mw in mod.get_module_middlewares():
            module_middlewares.append(mw)

app_middlewares = [
    RequestMiddleware(),
    SQLAlchemySessionMiddleware(),
]
app_middlewares.extend(module_middlewares)

log.info('Initialize Falcon WSGI application object.')
# Set default media type, used as value for the Content-Type
# header in responses.
wsgiapp = falcon.API(media_type='application/json; charset=utf-8',
                     middleware=app_middlewares)

# Let Falcon not automatically consume the request body stream,
# and decode form data. Do this manually, in the corresponding
# request handlers.
wsgiapp.req_options.auto_parse_form_urlencoded = False

# TODO(jp): make sure that URLPREFIX is documented to be required to start
# with a slash, and not to end with a slash.
assert config['URLPREFIX'].startswith('/')
assert not config['URLPREFIX'].endswith('/')


class RetryTransactions:
    """Retry Falcon responders that raise retryable database exceptions."""
    def __init__(self, resource):
예제 #28
0
class ItemsResource:
    def on_get(self, req, resp):
        params = req.params
        print(params)

        items = {'msg': params['msg'], 'Valence': 0.5, 'Arousal': 0.45}

        resp.status = falcon.HTTP_200
        resp.content_type = 'text/plain'
        resp.body = json.dumps(items, ensure_ascii=False)


class CORSMiddleware:
    def process_request(self, req, resp):
        resp.set_header('Access-Control-Allow-Origin', '*')
        resp.set_header('Access-Control-Allow-Methods', '*')
        resp.set_header('Access-Control-Allow-Headers', '*')
        resp.set_header('Access-Control-Max-Age', 1728000)


api = falcon.API(middleware=[CORSMiddleware()])
#api = falcon.API()
api.add_route('/prediction_api', ItemsResource())

if __name__ == "__main__":
    from wsgiref import simple_server

    httpd = simple_server.make_server("127.0.0.1", 8000, api)
    httpd.serve_forever()
예제 #29
0
import os

import falcon
import redis


def transform(req):
    zipcode = req.get_param('zip', required=True)
    date = req.get_param('date', required=True)
    hour = req.get_param('hour', required=True)

    return f'{zipcode}.{date}:{hour}'


class SunScreenerResource:
    def on_get(self, req, resp):
        key = transform(req)
        resp.status = falcon.HTTP_200
        resp.body = (r.get(key))


r = redis.from_url(os.environ.get("REDIS_URL"))
r.set('78701.20180608:0600', '0')

app = falcon.API()
sunscreener = SunScreenerResource()

app.add_route('/', sunscreener)
# ?zip=78701&date=20180608&hour=0600
예제 #30
0
 def make_api(self):
     """Create falcon api
     """
     api = falcon.API()
     return api