예제 #1
0
 def test_compile_keys(self):
     regex_string = '.*'
     compiled_regex = re.compile(regex_string)
     test_compile_dict = {'some_regex': regex_string}
     cors = CORS()
     cors._compile_keys(test_compile_dict, ['some_regex'])
     self.assertEqual(compiled_regex, test_compile_dict['some_regex'])
예제 #2
0
 def test_vary_origins_called(self):
     cors = CORS(allow_all_origins=True, allow_credentials_origins_list=['test.com'])
     cors._set_vary_origin = mock.Mock()
     origin = self.get_rand_str()
     headers = [('origin', origin)]
     self.simulate_cors_request(cors, headers=headers, preflight=False)
     cors._set_vary_origin.assert_called_once_with(self.resource.resp)
예제 #3
0
 def test_process_expose_headers(self):
     fake_req = mock.MagicMock()
     fake_resp = mock.MagicMock()
     cors = CORS(expose_headers_list=['test_header'])
     cors._process_expose_headers(fake_req, fake_resp)
     fake_resp.append_header.assert_called_once_with(
         'access-control-expose-headers', 'test_header'
     )
예제 #4
0
 def test_cors_disabled(self):
     self.resource = mock.MagicMock()
     self.resource.cors_enabled = False
     cors = CORS()
     cors.process = mock.Mock()
     self.simulate_cors_api(cors, '/')
     self.simulate_request('/', method='POST')
     self.assertEquals(cors.process.call_count, 0)
예제 #5
0
 def test_process_origin_return(self):
     cors = CORS(allow_origins_list=['test.com'])
     cors._process_origin = mock.Mock(return_value=False)
     cors._process_credentials = mock.Mock()
     headers = [('origin', 'rackspace.com')]
     self.simulate_cors_request(cors, headers=headers, preflight=False)
     self.assertEqual(cors._process_origin.call_count, 1)
     self.assertEqual(cors._process_credentials.call_count, 0)
예제 #6
0
 def test_no_requested_method(self):
     cors = CORS(allow_all_origins=True)
     cors._get_requested_headers = mock.Mock()
     cors._process_origin = mock.Mock(return_value=True)
     headers = [('origin', 'rackspace.com')]
     self.simulate_cors_request(cors, headers=headers,
                                preflight=True, add_request_method=False)
     self.assertEqual(cors._process_origin.call_count, 1)
     self.assertEqual(cors._get_requested_headers.call_count, 0)
예제 #7
0
 def test_method_not_allowed(self):
     cors = CORS(allow_all_origins=True, allow_methods_list=['GET'])
     cors._get_requested_headers = mock.Mock(return_value=True)
     cors._process_allow_headers = mock.Mock()
     headers = [('origin', 'rackspace.com')]
     self.simulate_cors_request(cors, headers=headers,
                                preflight=True, preflight_method='POST')
     self.assertEqual(cors._get_requested_headers.call_count, 1)
     self.assertEqual(cors._process_allow_headers.call_count, 0)
예제 #8
0
 def test_process_origin_allow_regex(self):
     fake_req = mock.MagicMock()
     fake_resp = mock.MagicMock()
     cors = CORS(allow_origins_regex='rack.*\.com')
     cors._set_allow_origin = mock.Mock()
     self.assertEqual(
         cors._process_origin(fake_req, fake_resp, 'rackspace.com'),
         True
     )
     cors._set_allow_origin.assert_called_once_with(fake_resp, 'rackspace.com')
예제 #9
0
 def test_process_origin_regex_none(self):
     fake_req = mock.MagicMock()
     fake_resp = mock.MagicMock()
     cors = CORS()
     cors._set_allow_origin = mock.Mock()
     self.assertEqual(
         cors._process_origin(fake_req, fake_resp, 'rackspace.com'),
         False
     )
     self.assertEqual(cors._set_allow_origin.call_count, 0)
예제 #10
0
 def test_process_allow_headers_regex(self):
     fake_req = mock.MagicMock()
     fake_resp = mock.MagicMock()
     cors = CORS(allow_headers_regex='.*_header')
     cors._set_allowed_headers = mock.Mock()
     self.assertEqual(
         cors._process_allow_headers(fake_req, fake_resp, ['test_header']),
         True
     )
     cors._set_allowed_headers.assert_called_once_with(fake_resp, ['test_header'])
예제 #11
0
 def test_process_credentials_origins_list(self):
     fake_req = mock.MagicMock()
     fake_resp = mock.MagicMock()
     cors = CORS(allow_credentials_origins_list=['rackspace.com'])
     cors._set_allow_credentials = mock.Mock()
     self.assertEqual(
         cors._process_credentials(fake_req, fake_resp, 'rackspace.com'),
         True
     )
     cors._set_allow_credentials.assert_called_once_with(fake_resp)
예제 #12
0
 def test_header_not_allowed(self):
     cors = CORS(allow_all_origins=True, allow_all_methods=True,
                 allow_headers_list=['test_header'])
     cors._process_methods = mock.Mock(return_value=True)
     cors._process_credentials = mock.Mock()
     headers = [
         ('origin', 'rackspace.com'),
         ('access-control-request-headers', 'not_allowed_header')
     ]
     self.simulate_cors_request(cors, headers=headers, preflight=True)
     self.assertEqual(cors._process_methods.call_count, 1)
     self.assertEqual(cors._process_credentials.call_count, 0)
예제 #13
0
 def test_process_credentials_called(self):
     cors = CORS(allow_all_origins=True, allow_all_methods=True, allow_all_headers=True)
     cors._process_methods = mock.Mock(return_value=True)
     cors._process_credentials = mock.Mock()
     headers = [('origin', 'rackspace.com')]
     self.simulate_cors_request(cors, headers=headers, preflight=True)
     # print(cors._process_methods.call_count)
     cors._process_credentials.assert_called_once_with(
         self.resource.req,
         self.resource.resp,
         'rackspace.com'
     )
예제 #14
0
 def test_process_allow_headers_disallow(self):
     fake_req = mock.MagicMock()
     fake_resp = mock.MagicMock()
     cors = CORS(allow_headers_list=['test_header'], allow_headers_regex='.*_header')
     cors._set_allowed_headers = mock.Mock()
     self.assertEqual(
         cors._process_allow_headers(
             fake_req, fake_resp, ['test_header', 'header_not_allowed']
         ),
         False
     )
     self.assertEqual(cors._set_allowed_headers.call_count, 0)
예제 #15
0
 def test_process_methods_resource(self):
     fake_req = mock.MagicMock()
     fake_resp = mock.MagicMock()
     fake_resource = mock.MagicMock()
     cors = CORS(allow_all_methods=True)
     cors._get_requested_method = mock.Mock(return_value='GET')
     cors._get_resource_methods = mock.Mock(return_value=['POST'])
     cors._set_allowed_methods = mock.Mock()
     self.assertEqual(
         cors._process_methods(fake_req, fake_resp, fake_resource),
         False
     )
     cors._set_allowed_methods.assert_called_once_with(fake_resp, ['POST'])
예제 #16
0
 def test_process_credentials_disallow(self):
     fake_req = mock.MagicMock()
     fake_resp = mock.MagicMock()
     cors = CORS(
         allow_credentials_origins_list=['not_rackspace'],
         allow_credentials_origins_regex='.*\.rackspace\..*'
     )
     cors._set_allow_credentials = mock.Mock()
     self.assertEqual(
         cors._process_credentials(fake_req, fake_resp, 'some_other_domain.lan'),
         False
     )
     self.assertEqual(cors._set_allow_credentials.call_count, 0)
예제 #17
0
 def test_process_origin_deny(self):
     fake_req = mock.MagicMock()
     fake_resp = mock.MagicMock()
     cors = CORS(
         allow_origins_list=['rackspace.com'],
         allow_origins_regex='rack.*\.com'
     )
     cors._set_allow_origin = mock.Mock()
     self.assertEqual(
         cors._process_origin(fake_req, fake_resp, 'not_rackspace.com'),
         False
     )
     self.assertEqual(cors._set_allow_origin.call_count, 0)
예제 #18
0
 def test_process_methods_not_requested(self):
     fake_req = mock.MagicMock()
     fake_resp = mock.MagicMock()
     fake_resource = mock.MagicMock()
     cors = CORS(allow_all_methods=True)
     cors._get_requested_method = mock.Mock(return_value=None)
     cors._set_allowed_methods = mock.Mock()
     self.assertEqual(
         cors._process_methods(fake_req, fake_resp, fake_resource),
         False
     )
     self.assertEqual(cors._set_allowed_methods.call_count, 0)
     cors._get_requested_method.assert_called_once_with(fake_req)
예제 #19
0
 def test_process_methods_notfound(self):
     fake_req = mock.MagicMock()
     fake_resp = mock.MagicMock()
     fake_resource = mock.MagicMock()
     cors = CORS(allow_methods_list=['GET', 'POST', 'PUT', 'DELETE'])
     cors._set_allowed_methods = mock.Mock()
     cors._get_requested_method = mock.Mock(return_value='POST')
     cors._get_resource_methods = mock.Mock(return_value=['GET', 'PUT'])
     self.assertEqual(
         cors._process_methods(fake_req, fake_resp, fake_resource),
         False
     )
     cors._set_allowed_methods.assert_called_once_with(fake_resp, ['GET', 'PUT'])
예제 #20
0
 def test_process_origin_allow_all(self):
     fake_req = mock.MagicMock()
     fake_resp = mock.MagicMock()
     cors = CORS(allow_all_origins=True)
     cors._set_allow_origin = mock.Mock()
     self.assertEqual(
         cors._process_origin(fake_req, fake_resp, 'rackspace.com'),
         True
     )
     cors._set_allow_origin.assert_called_once_with(fake_resp, '*')
     cors._set_allow_origin = mock.Mock()
     cors.supports_credentials = True
     self.assertEqual(
         cors._process_origin(fake_req, fake_resp, 'rackspace.com'),
         True
     )
     cors._set_allow_origin.assert_called_once_with(fake_resp, 'rackspace.com')
예제 #21
0
from falcon_cors import CORS

# from falcon_require_https import RequireHTTPS
# from falcon_multipart.middleware import MultipartMiddleware

middlewares = []

cors = CORS(allow_all_origins=['*'], allow_methods_list=['POST', 'PUT', 'GET'],
            allow_headers_list=['Content-Type', 'Accept', 'Authorization'], max_age=300)
middlewares.append(cors.middleware)

# middlewares.append(RequireHTTPS())
# middlewares.append(MultipartMiddleware())

예제 #22
0
 def test_no_origin_return(self):
     cors = CORS()
     cors._process_origin = mock.Mock()
     self.simulate_cors_request(cors, preflight=False)
     self.assertEqual(cors._process_origin.call_count, 0)
예제 #23
0
"""Main server entrypoint"""
import falcon
from falcon_auth import FalconAuthMiddleware, BasicAuthBackend
from falcon_cors import CORS

from auth import user_loader
from config import (CORS_ALLOWED_HEADERS, CORS_ALLOWED_METHODS,
                    CORS_ALLOWED_ORIGINS)
from resources import PayoutTimerResource

# Auth
auth_backend = BasicAuthBackend(user_loader)
auth_middleware = FalconAuthMiddleware(auth_backend)
# CORS
cors = CORS(allow_origins_list=CORS_ALLOWED_ORIGINS,
            allow_methods_list=CORS_ALLOWED_METHODS,
            allow_headers_list=CORS_ALLOWED_HEADERS)

app = falcon.API(middleware=[auth_middleware, cors.middleware])

payout = PayoutTimerResource()

app.add_route('/payouts', payout)
예제 #24
0
파일: app.py 프로젝트: trendiguru/core
from .temp_editor_users import USERS

login, auth_middleware = falcon_jwt.get_auth_objects(
    USERS.get,                              # get_users function
    "UPeQqp45xJeRgavxup8GzMTYTyDFwYND",     # random secret
    3600,                                   # expiration
    cookie_opts={"name": "fzz_auth_token",
                 "max_age": 86400,
                 "path": "/",
                 "http_only": True}
)


cors = CORS(allow_all_headers=True,
            # allow_all_origins=True,
            allow_origins_list=['http://localhost', 'http://localhost:8080', 'http://localhost:8000','http://editor.trendi.guru', 'https://editor-dot-test-paper-doll.appspot.com'],
            allow_credentials_origins_list=['http://localhost', 'http://localhost:8080', 'http://localhost:8000', 'http://editor.trendi.guru', 'https://editor-dot-test-paper-doll.appspot.com'],
            allow_all_methods=True)

api = falcon.API(middleware=[auth_middleware, cors.middleware])

editor = Editor()

api.add_route('/editor/images', editor)
api.add_route('/editor/images/{image_id}', editor)
api.add_route('/editor/images/{image_id}/people/{person_id}', editor)
api.add_route('/editor/images/{image_id}/people/{person_id}/items' ,editor)
api.add_route('/editor/images/{image_id}/people/{person_id}/items/{item_category}', editor)
api.add_route('/editor/images/{image_id}/people/{person_id}/items/{item_category}/similar_results/{results_collection}', editor)
api.add_route('/editor/images/{image_id}/people/{person_id}/items/{item_category}/similar_results/{results_collection}/{result_id}', editor)
api.add_route('/login', login)
예제 #25
0
    def on_get(self, req, resp):
        resp.status = falcon.HTTP_200
        resp.content_type = 'text/html'
        with open('docs/redoc.html', 'r') as f:
            resp.body = f.read()


class OpenAPISpecResource:
    def on_get(self, req, resp):
        resp.status = falcon.HTTP_200
        resp.content_type = 'text/html'
        with open('docs/swagger.yaml', 'r') as f:
            resp.body = f.read()


origins = [
    'https://ccsearch.creativecommons.org',
    'https://ccsearch-dev.creativecommons.org',
    'https://search.creativecommons.org'
]
cors = CORS(allow_origins_list=origins,
            allow_all_methods=True,
            allow_all_headers=True)
api = falcon.API(middleware=[cors.middleware])
api.add_route('/', RedocResource())
api.add_route('/swagger.yaml', OpenAPISpecResource())
api.add_route('/search_event', SearchEventResource())
api.add_route('/search_rating_event', SearchRatingEventResource())
api.add_route('/result_click_event', ResultClickEventResource())
api.add_route('/detail_page_event', DetailEventResource())
예제 #26
0
        except KeyError:
            raise falcon.HTTPBadRequest(
                'Missing thing',
                'A thing must be submitted in the request body.')

        proper_thing = self.db.add_thing(doc)

        resp.status = falcon.HTTP_201
        resp.location = '/%s/things/%s' % (user_id, proper_thing['id'])


cors = CORS(allow_origins_list=[
    'http://localhost:3000',
    'localhost:3000',
    'http://localhost:8000',
    'localhost:8000',
    'http://weather.lafiel.net',
],
            allow_all_methods=True,
            allow_all_headers=True)

app = falcon.API(middleware=[
    cors.middleware,
    RequireJSON(),
    JSONTranslator(),
])

stations = StationsResource(db)
measurements = MeasurementResource(db)
app.add_route('/api/stations', stations)
app.add_route('/api/stations/{name}', stations)
예제 #27
0
import falcon
from falcon_cors import CORS
import json
import os
from nn import process_image
from falcon_multipart.middleware import MultipartMiddleware

cors = CORS(allow_all_origins=True, allow_all_headers=True)
public_cors = CORS(allow_all_origins=True)
app = falcon.API(middleware=[cors.middleware, MultipartMiddleware()])


class Images(object):
    def on_post(self, req, resp):
        try:
            if not req.content_length:
                raise AssertionError('No content')
            req = json.load(req.stream)
            evaluation = process_image(req['image'])
            print(f'>> Evaluated: {evaluation}')
            resp.body = json.dumps({'resp_data': evaluation})
            resp.status = falcon.HTTP_200
        except Exception as e:
            resp.status = falcon.HTTP_204


class Index(object):
    def on_get(self, req, resp):
        resp.status = falcon.HTTP_200
        resp.content_type = 'text/html'
        with open('./frontend/build/index.html', 'r') as f:
예제 #28
0
파일: api.py 프로젝트: lgeo3/AIND-Isolation
        except Exception as e:
            resp.data = str(e)
            resp.status = falcon.HTTP_400

class IANextMove(object):
    def on_get(self, req, resp):
        print("Get with {} and resp {}".format(req, resp))
        next_move = game.do_ia_move()
        print("next ia moves is {}".format(next_move))
        resp.body = json.dumps(next_move, ensure_ascii=False)
        print(game.display_board())


ALLOWED_ORIGINS = ['http://localhost:8000'] # Or load this from a config file


cors = CORS(allow_methods_list=['POST', 'GET'], allow_origins_list=['http://127.0.0.1:8001'],  allow_credentials_all_origins=True, allow_all_headers=True)
game = Game()
api = falcon.API(middleware=[cors.middleware])
api.add_route("/v1/game_info", GameInfoRessource())
api.add_route("/v1/ia/next_move", IANextMove())
api.add_route("/v1/human/legal_moves", HumanPossibleMove())
api.add_route("/v1/human/move", HumanMove())

#g = Game()

from wsgiref import simple_server

if __name__ == '__main__':
    httpd = simple_server.make_server('127.0.0.1', 8000, api)
    httpd.serve_forever()
예제 #29
0
파일: servehss.py 프로젝트: nucleome/nucle
# Falcon follows the REST architectural style, meaning (among
# other things) that you think in terms of resources and state
# transitions, which map to HTTP verbs.
import multiprocessing
import argparse

import gunicorn.app.base

from gunicorn.six import iteritems
from falcon_cors import CORS
from nucle.nucle3d import hssreader
lis = [
    'http://vis.nucleome.org', 'https://vis.nucleome.org',
    'http://x7.andrew.cmu.edu:8080'
]
cors = CORS(allow_credentials_origins_list=lis, allow_origins_list=lis)


def help():
    return "host a hss file as web data service"


def set_parser(p):
    p.add_argument('-i',
                   '--input',
                   dest='input',
                   default='stdin',
                   type=str,
                   help="input file Default: %(default)s")
    p.add_argument('-p',
                   '--port',
예제 #30
0
        self.mongo_manager = MongoManager()
        self.redis_manager = RedisManager()
        self.account_manager = AccountManager(self.mongo_manager,self.redis_manager)
        self.question_manager = QuestionManager(self.mongo_manager,self.redis_manager,self.account_manager)

    def get_mongo_manager(self):
        return self.mongo_manager

    def get_redis_manager(self):
        return self.redis_manager

    def get_account_manager(self):
        return self.account_manager

    def get_question_manager(self):
        return self.question_manager

cors = CORS(allow_origins_list=['http://45.33.73.179:8888'])
api = falcon.API(middleware=[cors.middleware])

ap_manager = ApplicationManager()
#api_router = falcon.API()
cors = CORS(allow_origins_list=['http://45.33.73.179:8888'])
api_router = falcon.API(middleware=[cors.middleware])

api_router.add_route('/', default.DefaultWSGIHandler(ap_manager))
api_router.add_route('/login', login.LoginAPIHandler(ap_manager))
api_router.add_route('/auth', auth.AuthAPIHandler(ap_manager))
api_router.add_route('/question', question.QuestionAPIHandler(ap_manager))
api_router.add_route('/rank', rank.RankAPIHandler(ap_manager))
예제 #31
0
        ############ DEBUGGING ##############
        logging.debug("Sending response...")
        ############ _DEBUGGING ##############

        # Response to frontend
        resp.status = falcon.HTTP_200  # This is the default status
        resp.body = json.dumps(results, ensure_ascii=False)

        ############ DEBUGGING ##############
        logging.debug("Response sent !!!")
        ############ _DEBUGGING ##############


#---------- API settings -----------#
# falcon.API instances are callable WSGI apps
cors = CORS(allow_all_origins=True)  # Allow access from frontend
app = falcon.API(middleware=[cors.middleware])

# Resources are represented by long-lived class instances
searchGloss = Query()

# things will handle all requests to the '/things' URL path
app.add_route('/query', searchGloss)

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

    port = 1420
    print(f"Start serving at http://localhost:{port}")
    httpd = simple_server.make_server('localhost', port, app)
    httpd.serve_forever()
예제 #32
0
import falcon
from falcon_cors import CORS
import json
import logging
import sys
from app.bjj_name import get_last_name, update_first_name

cors = CORS(allow_origins_list=[
    'http://localhost:3000',
    'http://bjj-name-ui.s3-website-us-east-1.amazonaws.com'
],
            allow_headers_list=['Content-Type'],
            allow_methods_list=['POST', 'GET'])

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


class PingResource(object):
    def on_get(self, req, resp):
        resp.status = falcon.HTTP_200
        resp.body = (json.dumps({"ping": 'Pong yo.'}))


class NameResource(object):
    def __init__(self):
        self.logger = logging.getLogger('bjjnameapp.' + __name__)

    def on_post(self, req, resp):
        body = json.loads(req.stream.read())
        resp.status = falcon.HTTP_201
        first_name = update_first_name(body['first_name'])
예제 #33
0
import falcon
from falcon_cors import CORS
from services.api.parse.entity_extraction import EntityExtraction
from falcon_multipart.middleware import MultipartMiddleware
from services.api.common.exception_handler import set_exception_handlers
from services.api.parse.docLinking_process import DocLinking_process
from services.api.common.logger import set_up_logging
logger = set_up_logging(__name__)
import warnings
warnings.filterwarnings("ignore")

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

dl_middlewares = [MultipartMiddleware(), cors.middleware]

api = application = falcon.API(middleware=dl_middlewares)

#doc linking
doc_link = DocLinking_process()
api.add_route('/doclinking', doc_link)

entity_extractor = EntityExtraction()
api.add_route('/msa_entities', entity_extractor)
logger.info("#####################")
logger.info("Application is ready")
logger.info("#####################")
set_exception_handlers(api)
예제 #34
0
import json
import re

import falcon
import pymongo
import requests
from bson import ObjectId
from bson.errors import InvalidId
from falcon_cors import CORS

from weatheh import utils

MONGO_DB_NAME = "weatheh"

cors = CORS(allow_origins_list=["http://127.0.0.1:8080"])
api = application = falcon.API(middleware=[cors.middleware])
session = requests.Session()

client = pymongo.MongoClient()
db = client[MONGO_DB_NAME]
stations_coll = db.stations
cities_coll = db.cities

# db.drop_collection("forecasts")
# forecasts_coll = db.forecasts
# db.forecasts.create_index("datetime", expireAfterSeconds=120)


# noinspection PyMethodMayBeStatic
class City:
    def on_get(self, req, resp, city_code):
예제 #35
0
파일: app.py 프로젝트: ZzAntares/pypriorapi
import falcon
from falcon_cors import CORS
import order
import upload
import trellohandler

cors = CORS(allow_all_origins=True,
            allow_origins_list=[
                'http://localhost:8000', 'http://localhost:8080',
                'http://52.34.119.6'
            ],
            allow_methods_list=['POST', 'GET', 'PUT'])

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

order_collection = order.Collection()
upload_collection = upload.Collection()
board_collection = trellohandler.Boards()
lists_collection = trellohandler.Lists()
cards_collection = trellohandler.Cards()

api.add_route('/order/', order_collection)
api.add_route('/order/{token}', order_collection)
api.add_route('/upload/{token}', upload_collection)
api.add_route('/board/', board_collection)
api.add_route('/list/{board}', lists_collection)
api.add_route('/card/{lst}', cards_collection)
예제 #36
0
            writeData(db)
            res.media = { 'data': db[index] }
        except Exception as ex:
            print(ex)
            res.media = { 'error': 'Faild to save data'}
            res.status = falcon.HTTP_400

    def on_delete(self, req, res, id = None):
        try:
            db = getData()
            index = findIndex(db, 'id', id)
            
            if index < 0:
                raise Exception()

            db.remove(db[index])
            writeData(db)
            res.media = { 'data': id }
        except Exception as ex:
            print(ex)
            res.media = { 'error': 'Faild to save data'}
            res.status = falcon.HTTP_400


API_PREFIX = '/api/v1'
cors = CORS(allow_all_origins=True)
api = falcon.API(middleware=[cors.middleware])
api.add_route(API_PREFIX + '/user', MockAPI());
api.add_route(API_PREFIX + '/user/{id}', MockAPI());

예제 #37
0
import falcon
from falcon_cors import CORS

cors = CORS(allow_methods_list=['GET', 'POST', 'OPTIONS', 'PUT', 'DELETE'])

app = falcon.API(middleware=[cors.middleware])
예제 #38
0
파일: api.py 프로젝트: Wauplin/robotoff
        else:
            resp.status = falcon.HTTP_204


class UserStatisticsResource:
    def on_get(self, req: falcon.Request, resp: falcon.Response,
               username: str):
        annotation_count = (UserAnnotation.select().where(
            UserAnnotation.username == username).count())
        resp.media = {"count": {"annotations": annotation_count}}


cors = CORS(
    allow_all_origins=True,
    allow_all_headers=True,
    allow_all_methods=True,
    allow_credentials_all_origins=True,
    max_age=600,
)

api = falcon.API(middleware=[
    cors.middleware,
    MultipartMiddleware(),
    DBConnectionMiddleware()
])
# Parse form parameters
api.req_options.auto_parse_form_urlencoded = True
api.req_options.strip_url_path_trailing_slash = True
api.req_options.auto_parse_qs_csv = True
api.add_route("/api/v1/insights/{barcode}", ProductInsightResource())
api.add_route("/api/v1/insights/detail/{insight_id:uuid}",
예제 #39
0
def get_allowed():
    rest_url = 'localhost:8555'
    if 'ALLOW_ORIGIN' in environ:
        allow_origin = environ['ALLOW_ORIGIN']
        host_port = allow_origin.split('//')[1]
        host = host_port.split(':')[0]
        port = str(int(host_port.split(':')[1]))
        rest_url = host + ':' + port
    else:
        allow_origin = ''
    return allow_origin, rest_url


allow_origin, rest_url = get_allowed()
cors = CORS(allow_origins_list=[allow_origin])
public_cors = CORS(allow_all_origins=True)


class MockController:
    """
    On get, returns random integer from
    1 to 10.
    """
    @staticmethod
    def on_get(req, resp):
        resp.body = json.dumps(random.randint(1, 10))


api = falcon.API(middleware=[cors.middleware])
api.add_route('/v1/mock_controller/poll', MockController())
예제 #40
0
import json
import waitress
from data import Data
from torch.utils.data import DataLoader
from utils import load_torch_model
from model import BertForClassification, CharCNN
from evaluate import evaluate
import time
from classmerge import class_case
from dataclean import cleanall, shortenlines

logging.basicConfig(level=logging.INFO, format='%(asctime)-18s %(message)s')
logger = logging.getLogger()
cors_allow_all = CORS(allow_all_origins=True,
                      allow_origins_list=['*'],
                      allow_all_headers=True,
                      allow_all_methods=True,
                      allow_credentials_all_origins=True)

parser = argparse.ArgumentParser()
parser.add_argument('-p', '--port', default=58082, help='falcon server port')
parser.add_argument('-c',
                    '--config_file',
                    default='config/bert_config.json',
                    help='model config file')
args = parser.parse_args()
model_config = args.config_file

MODEL_MAP = {'bert': BertForClassification, 'cnn': CharCNN}

예제 #41
0
import ptvsd
import falcon
import tasks
from falcon_cors import CORS

# ptvsd.enable_attach("my_secret", address=('localhost', 4000))

cors = CORS(allow_origins_list=["http://localhost:3000"])
APP = application = falcon.API(middleware=[cors.middleware])

TASK_MANAGER = tasks.TaskManager()
TASKS_HANDLER = tasks.CollectionHandler(TASK_MANAGER)
TASK_HANDLER = tasks.ItemHandler(TASK_MANAGER)

APP.add_route('/api/tasks', TASKS_HANDLER)
APP.add_route('/api/tasks/{_id}', TASK_HANDLER)
예제 #42
0
class RedirectToGrafana(object):
    """
    This is a 301 re-direction to Grafana UI
    """
    def __init__(self):
        super(RedirectToGrafana, self).__init__()

    def on_get(self, req, resp):
        resp.status = falcon.HTTP_301
        resp.set_header('Location', 'http://localhost:3001')


prom = ProtonPrometheus()
cors = CORS(
    allow_all_origins=True,
    allow_all_headers=True,
    allow_all_methods=True,
)
app = falcon.API(
    middleware=[TokenAuthenticator(), cors.middleware,
                Iface_watch(), prom])

app.add_route('/', DefaultRouteHandler())
app.add_route('/fast-serve', FastServe())
app.add_route('/login', IctrlProtonLogin())
app.add_route('/signup', IctrlProtonSignup())
app.add_route('/reset', IctrlProtonPasswordReset())
app.add_route('/metrics', prom)
app.add_route('/proton-prom', RedirectToProm())
app.add_route('/proton-grafana', RedirectToGrafana())
예제 #43
0
import falcon
import get_score
import defaultplayers
from falcon_cors import CORS

cors = CORS(allow_origins_list=['http://localhost:3000'],allow_all_origins=True, allow_all_headers=True, allow_all_methods=True, allow_credentials_all_origins=True)
api = application =falcon.API(middleware=[cors.middleware])

score = get_score()
defaultplayers = defaultplayers()

api.add_route('/get_score', score)
api.add_route('/get_defaultplayers', defaultplayers)




예제 #44
0
def get_allowed():
    rest_url = 'localhost:28000'
    if 'ALLOW_ORIGIN' in environ:
        allow_origin = environ['ALLOW_ORIGIN']
        host_port = allow_origin.split('//')[1]
        host = host_port.split(':')[0]
        port = str(int(host_port.split(':')[1]))
        rest_url = host + ':' + port
    else:
        allow_origin = ''
    return allow_origin, rest_url


allow_origin, rest_url = get_allowed()
cors = CORS(allow_all_origins=True)
public_cors = CORS(allow_all_origins=True)


class db_database_names(PoseidonStorage):
    """
    Request:
        URL:        /v1/storage/
        Method:     GET
    Response:
        Body:       json encoded list of db names
    """
    def on_get(self, req, resp):
        try:
            ret = self.client.database_names()
        except:  # pragma: no cover
예제 #45
0
 def test_process_max_age(self):
     fake_req = mock.MagicMock()
     fake_resp = mock.MagicMock()
     cors = CORS(max_age=5)
     cors._process_max_age(fake_req, fake_resp)
     fake_resp.set_header.assert_called_once_with('access-control-max-age', 5)
예제 #46
0
 def test_set_very_origin(self):
     fake_resp = mock.MagicMock()
     cors = CORS()
     cors._set_vary_origin(fake_resp)
     fake_resp.append_header.assert_called_once_with('vary', 'origin')
예제 #47
0
__author__ = "Thilo Wehrmann, Steffen Gebhardt"
__copyright__ = "Copyright 2016, EOSS GmbH"
__credits__ = ["Thilo Wehrmann", "Steffen Gebhardt"]
__license__ = "GPL"
__version__ = "1.0.0"
__maintainer__ = "Thilo Wehrmann"
__email__ = "*****@*****.**"
__status__ = "Production"

import falcon
from falcon.routing import DefaultRouter
from falcon_cors import CORS

# TODO: Right now everything is allowed; finer specification will be better
cors = CORS(allow_all_origins='*',
            allow_methods_list=['GET', 'POST', 'OPTIONS'],
            allow_all_headers=True,
            allow_credentials_all_origins=True)


class RequireJSON(object):
    """
    Falcon middleware which checks json conditions for each requests
    """
    def process_request(self, req, resp):
        if not req.client_accepts_json:
            raise falcon.HTTPNotAcceptable(
                'This API only supports responses encoded as JSON.',
                href='http://docs.examples.com/api/json')

        if req.method in ('POST', 'PUT'):
            if req.content_type is None:
예제 #48
0
파일: main.py 프로젝트: Muurtegel/anfora
from api.v1.activityPub.outbox import (Outbox)
from api.v1.activityPub.followers import (Followers)

from api.v1.server import (wellknownNodeinfo, wellknownWebfinger, nodeinfo, hostMeta)

#Auth
from auth import (auth_backend,loadUser)

#URLs
from urls import urls

from api.v1.server import serverInfo

cors =  CORS(allow_all_origins=True,
            allow_all_methods=True,
            allow_headers_list=['*'],
            log_level='INFO',
        )

#Auth values
auth_middleware = FalconAuthMiddleware(auth_backend,exempt_methods=['OPTIONS'])


#Create the app
app = falcon.API(middleware=[
    #cors.middleware,
    CorsMiddleware(),
    auth_middleware,
    PeeweeConnectionMiddleware(),
    MultipartMiddleware(),
])
예제 #49
0
 def test_set_allowed_methods(self):
     fake_resp = mock.MagicMock()
     allowed_method_list = ['GET']
     cors = CORS()
     cors._set_allowed_methods(fake_resp, allowed_method_list)
     fake_resp.append_header.assert_called_once_with('access-control-allow-methods', 'GET')
예제 #50
0
        task_scan = classify_numbers.delay(serialized_number_images)
        resp.status = falcon.HTTP_202
        resp.body = json.dumps({
            'id_task_scan': task_scan.id
        })


class SudokuSolveItem(object):
    def on_get(self, req, resp, scan_id):
        scan_result = AsyncResult(scan_id)
        result = {
            'status': scan_result.status,
            'scan_result': scan_result.result
        }
        resp.status = falcon.HTTP_200

        resp.body = json.dumps(result)


images = SudokuSolveResource()
app = falcon.API(middleware=[
    CORS(
        allow_all_origins=True,
        allow_all_methods=True,
        allow_all_headers=True
    ).middleware
])
app.add_route('/sudoku-solve', images)
app.add_route('/sudoku-solve/{scan_id}', SudokuSolveItem())

예제 #51
0
#             username = requestBody.get('username')
#             password = requestBody.get('password')

#             if username == 'hello' and password == 'world':
#                 res.body = json.dumps({
#                     'id_number': 100000,
#                     'last_name': 'Jacob Yap',
#                     'first_name': 'Mabry Baeron Jackyle',
#                     'course': 'BS CoE/ MS CS',
#                     'year': 5
#                 })
#         else:
#             res.status = falcon.HTTP_400

# Allow CORS
cors = CORS(allow_origins_list=['http://localhost:3000'])

# falcon.API instances are callable WSGI apps
app = falcon.API(middleware=[
    SQLAlchemySessionManager(Session),
    cors.middleware,
])

from resources import model

# set x-www-form-urlencoded to be available with req.params
app.req_options.auto_parse_form_urlencoded = True

# Resources are represented by long-lived class instances
data = DataResource()
predict = EarthquakePredictionResource()
예제 #52
0
from falcon import HTTP_201
from falcon import HTTP_202
from falcon import HTTP_404
from falcon import API
#import boto3
import uuid
import time
import traceback
import requests

from sets import Set
from collections import defaultdict

# cors
from falcon_cors import CORS
cors = CORS(allow_all_origins=True, allow_all_methods=True)
public_cors = CORS(allow_all_origins=True)


def do_something(guid, data):
    print "GUID", guid
    print "DATA: ", data


# dict for maintaining guids
allowed_guids = Set()
guid_details = {}
guid_files = defaultdict(lambda: "")


class UploadHandler:
예제 #53
0
파일: main.py 프로젝트: poojapruthvi/PROTON
        resp.body = json.dumps(response)
        resp.status = falcon.HTTP_200

class FastServe(object):
    """
    This is a sink to service dynamically routed entries from cache!
    """

    def __init__(self):
        super(FastServe, self).__init__()

    def on_get(self, req, resp):
        resp.status = falcon.HTTP_200


cors = CORS(allow_all_origins=['http://localhost:3000'])
app = falcon.API(middleware=[cors.middleware, Iface_watch()])

app.add_route('/', DefaultRouteHandler())
app.add_route('/fast-serve', FastServe())





# Open API Specs
spec = APISpec(
    title='PROTON STACK',
    version='1.0.0',
    openapi_version='2.0',
    plugins=[
예제 #54
0
import falcon
from controllers.students import Student
from falcon_cors import CORS

cors = CORS(allow_all_origins=True,
            allow_all_headers=True,
            allow_methods_list=['GET', 'POST', 'OPTIONS', 'PUT', 'DELETE'])

app = falcon.API(middleware=[cors.middleware])

app.add_route('/students', Student())