def __init__(self):
     super(HTTP,self).__init__(middleware=[MultipartMiddleware()]) 
     self.req_options = self._get_request_options()
     self._host = None
     self._port = 0
     self._endpoints = {}
     self._statistics = {}
Пример #2
0
def server_main():
    logger = logger_func.mylogger("server_main", '../log/server.log')
    ## https://codeday.me/jp/qa/20190301/342294.html
    ## stdout,stderrをlogger出力
    sys.stdout = logger_func.LoggerWriter(logger.debug)
    sys.stderr = logger_func.LoggerWriter(logger.warning)

    try:
        from wsgiref import simple_server
        ## Upload API
        ## Ref https://qiita.com/komakomako/items/5ba6a1b2a582464a7748
        ##
        apiserver = falcon.API(
            middleware=[api_class.CORSMiddleware(),
                        MultipartMiddleware()])
        #https://stackoverflow.com/questions/48679165/python-falcon-get-post-data
        apiserver.req_options.auto_parse_form_urlencoded = True
        apis = []
        apis.append(api_class.Sample())
        apis.append(api_class.UploadSample())
        apis.append(api_class.PostSample())

        for api in apis:
            apiserver.add_route(api.uri, api)
        httpd = simple_server.make_server("0.0.0.0", 18888, apiserver)
        httpd.serve_forever()
    except KeyboardInterrupt:
        sys.exit(0)
    except:
        import traceback
        logger.error(traceback.format_exc())
Пример #3
0
def create_app(mgr: Manager):
    logging.basicConfig(filename="/var/tmp/webservices_api.log",
                        level=logging.INFO)
    logging.info("Service initialized")
    print("Service initialized", file=sys.stderr)

    manager = mgr
    app = application = falcon.App(middleware=[MultipartMiddleware()])

    # Provided for backwards compatibility
    #scNetViz = ScNetVizHandler(mgr)
    #api.add_route('/scnetviz/api/v1/umap', scNetViz)
    #api.add_route('/scnetviz/api/v1/tsne', scNetViz)
    #api.add_route('/scnetviz/api/v1/drawgraph', scNetViz)
    #api.add_route('/scnetviz/api/v1/louvain', scNetViz)
    #api.add_route('/scnetviz/api/v1/leiden', scNetViz)

    # New API
    jobs = Jobs(mgr)
    app.add_route('/status/{job_id}', jobs)
    app.add_route('/fetch/{job_id}', jobs)
    app.add_route('/terminate/{job_id}', jobs)
    algorithms = Algorithms(jobs)
    app.add_route('/services', algorithms)
    for algorithm in algorithms.get_algorithms():
        app.add_route('/service/' + algorithm,
                      algorithms.get_algorithm(algorithm))

    # ChimeraX web services
    from . import cxservices
    cxservices.add_routes(app)

    return application
Пример #4
0
    def __init__(self, web_path: WebPathStructure = WebPathStructure()):
        self._api = falcon.API(middleware=[MultipartMiddleware()])
        self._api.req_options.auto_parse_form_urlencoded = True
        self.web_path = web_path

        # add static routing functionality
        self._api.add_static_route(prefix='/', directory=str(web_path.frontend_dir_absolute), downloadable=True)
        self._api.add_route('/', StaticResource(Path(web_path.frontend_dir_absolute) / 'index.html'))

        self._populate_frontend()
Пример #5
0
def create_app(file_store):
    middleware = [Middleware(), MultipartMiddleware()]
    api = falcon.API(middleware=middleware)
    api.add_route('/v1/api/users', UserCollection())
    api.add_route('/v1/api/password-reset-request',
                  PasswordResetRequestResource())
    api.add_route('/v1/api/password-reset', PasswordResource())
    api.add_route('/v1/api/{username}/files', FileCollection(file_store))
    api.add_route('/v1/api/files/{filename}', File(file_store))
    return api
Пример #6
0
def create_server(service_json):
    app = falcon.API(middleware=[MultipartMiddleware()])

    gateway = GatewayUtil(service_json)

    urls = gateway.urls
    for url in urls:
        resource = GatewayResource(url["service_url"], url["jwt_secure"])
        app.add_route(url["url"], resource)

    return app, urls
Пример #7
0
def init_client(service_name):
    """
    init dummy client for testing.
    Args:
        service_name(str):  the service name
    Returns:
        client for testing
    """
    app = falcon.API(middleware=[MultipartMiddleware()])
    server.serve.set_server_properties(app, service_name)
    return testing.TestClient(app)
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--port', type=int, default=8000)
    args = parser.parse_args()

    api = falcon.API(middleware=[MultipartMiddleware()])
    api.add_route('/', IndexHandler())
    api.add_route('/upload', ApiHandler())
    api.add_static_route('/script', os.path.abspath('./script'))
    api.add_static_route('/sound', os.path.abspath('./sound'))
    print('Serving on 0.0.0.0:%d' % args.port)
    simple_server.make_server('0.0.0.0', args.port, api).serve_forever()
Пример #9
0
def create():

    """Create the API endpoints."""
    cors = CORS(allow_all_origins=True,allow_all_methods=True, allow_all_headers=True)
    app = falcon.API(middleware=[cors.middleware, MultipartMiddleware()])

    dm = DataManager(InMemoryStorage(), InMemoryStorage(), data_folder, lcdURL, lcdPort)


    app.add_route('/annotatedFiles', AnnotatedFiles(dm))
    app.add_route('/annotatedFiles/json', AnnotatedFilesJSON(dm))
    app.add_route('/publications', GetPublications(dm))

    app.add_route('/expression', CubeExpressions(dm))
    app.add_route('/corpus', CubeCorpora(dm))
    app.add_route('/genre', CubeGenres(dm))
    app.add_route('/function', CubeFunctions(dm))

    app.add_route('/corpus/groups', GroupCorpora(dm))
    app.add_route('/expression/groups', GroupExpressions(dm))
    app.add_route('/function/groups', GroupFunctions(dm))
    app.add_route('/genre/groups', GroupGenres(dm))

    app.add_route('/groups', Groups(dm))


    app.add_route('/obs/filtered', FilteredObservations(dm))
    app.add_route('/obs/filtered/query', QueryFilteredObservations(dm))
    app.add_route('/obs/filtered/result', FilteredResultObservations(dm))

    app.add_route('/obs/filtered/preview', FilteredObservationsPreview(dm))

    app.add_route('/infer', Infer(dm))


    app.add_route('/cc/filtered', CCFiltered(dm))

    app.add_route('/normalize', Normalize(dm))
    app.add_route('/obs/norm2', CreateNormalizedCube(dm))
    app.add_route('/obs/norm/query', QueryNormalizedCube(dm))
    app.add_route('/obs/norm/defs', NormalizedCubeDefinitions(dm))

    app.add_route('/obs/excluded', ExcludedObservations(dm))
    app.add_route('/pub/excluded', ExcludedPublications(dm))


    app.add_route('/image', Image(image_folder))

    app.add_route('/lcd/status', CheckForLCDConnection(dm))

    main_logger.info('App2 is running.')
    return app
Пример #10
0
def create_docker_app(global_config):
    import falcon
    from falcon_multipart.middleware import MultipartMiddleware

    api = falcon.API(middleware=[MultipartMiddleware()])

    api.req_options.strip_url_path_trailing_slash = True
    download_dir = dict(global_config).get('download_dir', '/tmp')
    api.add_route('/api/ear/conf/template/', Template())
    api.add_route('/api/ear/conf', GenerateConf(download_dir))
    api.add_route('/api/ear/conf/upload', ParseConf())

    return api
Пример #11
0
    def __init__(self, *args, **kwargs):

        super().__init__(*args, **kwargs)

        self.multipart_middleware = MultipartMiddleware()

        self.auth_backend = TokenAuthBackend(user_loader, auth_header_prefix='Token')
        
        self.auth_middleware = FalconAuthMiddleware(self.auth_backend,
            exempt_routes=['/api/login'], exempt_methods=['HEAD'])

        self.auth = False
        self.cors_origins = list()
Пример #12
0
def create_app():
    setup_logging()

    app = falcon.API(
        middleware=[
            CrossDomain(),
            # JSONTranslator(),
            MultipartMiddleware()
        ], )

    app.add_error_handler(Exception, error_handler)

    _setup_routes(app)

    return app
Пример #13
0
def create_app(db, image_store, vision_api):
    setup_logger('output.log')

    api = falcon.API(
        middleware=[AuthMiddleware(),
                    MultipartMiddleware(),
                    RequireJSON()])

    database = Database(db)
    api.add_route(database.PATH, database)

    collection = Collection(image_store)
    api.add_route(collection.PATH, collection)
    api.add_route(CollectionItem.PATH, CollectionItem(image_store))

    api.add_route(Vision.PATH, Vision(vision_api))
    return api
class server(object):
  def _request_valid():
      # validate request here
  
  def on_get(self,req,resp,action):
      
      if(self._request_valid()):
        # do processing of request
        resp.status = falcon.HTTP_200
        resp.content_type = "text/html"
        resp.body = "Success"
      else:
        resp.status = falcon.HTTP_401
        resp.content_type = "text/html"
        resp.body = "Failure"
        
  def on_post(self,req,resp,action):
      if(self._request_valid()):
        # do processing of request
        resp.status = falcon.HTTP_200
        resp.content_type = "text/html"
        resp.body = "Success"
      else:
        resp.status = falcon.HTTP_401
        resp.content_type = "text/html"
        resp.body = "Failure"

cors = CORS(allow_all_origins=True)
app = falcon.API(media_type='application/json,charset=UTF-8',
                  middleware=[
                          cors.middleware,
                          custom_middleware(),
                          MultipartMiddleware()
                          ])
app.add_error_handler(global_error_handler,global_error_handler.handle)
app.add_route("/demo",server())
server_config = {
  'server.socket_host' : '0.0.0.0',
  'server.socket_port' : 8080'
  
  }

if __name__ = "main":
  cherrypy.config.update(server_config)
  cherrypy.tree.graft(app,'/')
  cherrypy.engine.start()
Пример #15
0
    def __init__(self, config):

        self.config = config

        shared_secret = os.getenv(AUTH_SHARED_SECRET_ENV, 'uggipuggi')
        
        COOKIE_OPTS = {"name": "auth_token",
                       "location": "header",
                       #"max_age": MAX_TOKEN_AGE,
                       "path": "/recipes",
                       "http_only": True}        

        # LoginResource, AuthMiddleware
        self.forgot_password, self.register, self.logout, self.pw_change, self.verify_phone, self.auth_middleware = auth_jwt.get_auth_objects(
            get_user,
            shared_secret, # random secret
            TOKEN_EXPIRATION_SECS,
            VERIFY_PHONE_TOKEN_EXPIRATION_SECS,
            token_opts=COOKIE_OPTS
        )
        
        cors = CORS(
            allow_all_origins=True,
            allow_all_headers=True,            
            allow_all_methods=True,
            allow_credentials_all_origins=True
        )
        
        self.prometheus_metrics = PrometheusMiddleware()
        self.app = falcon.API(middleware=[cors.middleware,
                                          MultipartMiddleware(),
                                          self.auth_middleware,
                                          self.prometheus_metrics])

        if SERVER_RUN_MODE == 'DEBUG':
            self.logger = self._set_logging()
        else:
            self.logger = init_logger() 
        self.logger.info("")
        self.logger.info("===========")
        self.logger.info(time.strftime("%c"))
        self.logger.info("===========")
        self._setup_db()
        self._load_routes()
Пример #16
0
    def __init__(self):
        self.app = falcon.API(middleware=[
            # middleware.RequireJSON(),
            # middleware.JSONTranslator(),
            MultipartMiddleware(),
            BeginSQL()
        ])
        self.app.add_error_handler(Exception, handler=App.error_handle)

        r_file = RFile()
        r_path = RPath()
        r_path_upload = RPathUpload()
        r_admin = RAdmin()
        self.app.add_route('/file/{file_id}', r_file)
        self.app.add_route('/path/{path_id}', r_path)
        self.app.add_route('/path/', r_path)
        self.app.add_route('/upload/path/{path_id}', r_path_upload)
        self.app.add_route('/upload/path/', r_path_upload)
        self.app.add_route('/admin', r_admin)
Пример #17
0
    def __init__(self):

        cors = CORS(allow_all_origins=True)

        super(Service, self).__init__(
            middleware=[cors.middleware, MultipartMiddleware(), ContextMiddleware(), LogMiddleware()]
        )

        self.BASE_PATH = '/nbi/catalogue/api'

        # Build routes
        resources = __find_resources__()
        exclude_list = ConfReader().get_list('API', 'exclude_apis')
        if len(exclude_list) > 0:
            resources = list(
                filter(lambda api: api.__name__ not in exclude_list, resources)
            )
        for r in resources:
            r.initialize()
            instance = r()
            for route in r.ROUTES:
                self.add_route(self.BASE_PATH + route, instance)
Пример #18
0
def create_app(mgr: Manager):
    manager = mgr
    api = falcon.API(middleware=[MultipartMiddleware()])

    # Provided for backwards compatibility
    api.add_route('/scnetviz/api/v1/umap', ScNetVizHandler())
    api.add_route('/scnetviz/api/v1/tsne', ScNetVizHandler())
    api.add_route('/scnetviz/api/v1/drawgraph', ScNetVizHandler())
    api.add_route('/scnetviz/api/v1/louvain', ScNetVizHandler())
    api.add_route('/scnetviz/api/v1/leiden', ScNetVizHandler())

    # New API
    jobs = Jobs(mgr)
    api.add_route('/status/{job_id}', jobs)
    api.add_route('/fetch/{job_id}', jobs)
    api.add_route('/terminate/{job_id}', jobs)
    algorithms = Algorithms(jobs)
    api.add_route('/services', algorithms)
    for algorithm in algorithms.get_algorithms():
        api.add_route('/service/' + algorithm,
                      algorithms.get_algorithm(algorithm))

    return api
Пример #19
0
from .audio_name import AudioName
from .image import Image
from .image_name import ImageName
from .skybox import Skybox
from .script import Script
from .script_name import ScriptName

cors = CORS(allow_origins_list=[
    'http://localhost:8100', 'http://127.0.0.1:8100',
    'http://kalegaurd.local:8100', 'http://192.168.100.17:8100'
],
            allow_all_headers=True,
            allow_all_methods=True)
#api = application = falcon.API(middleware=[RequireHTTPS(), cors.middleware, MultipartMiddleware()])
api = application = falcon.API(
    middleware=[cors.middleware, MultipartMiddleware()])

data_store = DataStore()
website = Website()
websites = Websites()
page = Page()
export = Export()
model = Model()
model_name = ModelName()
model_version = ModelVersion()
light_version = LightVersion()
audio = Audio()
audio_name = AudioName()
image = Image()
image_name = ImageName()
skybox = Skybox()
Пример #20
0
logging.info('configuring falcon')


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 falcon.HTTPStatus(falcon.HTTP_200, body='\n')


# falcon.API instances are callable WSGI apps
app = falcon.API(middleware=[HandleCORS(), MultipartMiddleware()])

# Determine whether the input file is a multi-config (i.e. paths to multiple files) or a single config file
with open(meta_config_path, 'r') as meta_config:
    first_line = meta_config.readline().strip('\r\n')
    if first_line != METACONF_FLAG:
        conf_files = [meta_config_path]
        map_services = {'_multi_map': False}
    else:
        conf_files = re.split('[\\r\\n]+', meta_config.read(
        ))  # Note that the .readline() above means we skip the first line
        map_services = {'_multi_map': True}

# Start up a set of services (i.e. a MapService) for each map (as specified by its config file)
for path in conf_files:
    if path == '':
Пример #21
0
#!/usr/bin/env python3
import bjoern
import falcon

from falcon_cors import CORS
from falcon_multipart.middleware import MultipartMiddleware

import routes


cors = CORS(allow_all_origins=True, allow_all_methods=True, allow_all_headers=True)
api = application = falcon.App(middleware=[cors.middleware, MultipartMiddleware()])

r = routes.routes()
for route in r:
    api.add_route(routes.version()+route, r[route])


if __name__ == "__main__":
    bjoern.run(api, "0.0.0.0", 5001)
Пример #22
0
import falcon
import sciwing.api.conf as config
from sciwing.api.resources.sect_label_resource import SectLabelResource
from sciwing.api.resources.parscit_tagger_resource import ParscitTaggerResource
from sciwing.api.resources.science_ie_tagger_resource import ScienceIETaggerResource
from sciwing.api.pdf_store import PdfStore
from falcon_multipart.middleware import MultipartMiddleware

# A few initialization
multipart_middleware = MultipartMiddleware()

PDF_STORE_LOCATION = config.PDF_STORE_LOCATION
BIN_FOLDER = config.BIN_FOLDER
PDF_BOX_EXEC = BIN_FOLDER.joinpath("pdfbox-app-2.0.16.jar")

# model paths and infer functions
SECT_LABEL_MODEL_PATH = config.SECT_LABEL_MODEL_PATH
SECT_LABEL_INFER_FUNCTION = config.SECT_LABEL_INFER_FUNCTION

PARSCIT_TAGGER_MODEL_PATH = config.PARSCIT_TAGGER_MODEL_PATH
PARSCIT_TAGGER_INFER_FUNCTION = config.PARSCIT_TAGGER_INFER_FUNCTION

SCIENCE_IE_TAGGER_MODEL_PATH = config.SCIENCE_IE_TAGGER_MODEL_PATH
SCIENCE_IE_TAGGER_INFER_FUNCTION = config.SCIENCE_IE_TAGGER_INFER_FUNCTION

api = application = falcon.API(middleware=[multipart_middleware])
pdf_store = PdfStore(store_path=PDF_STORE_LOCATION)

sect_label_resource = SectLabelResource(
    pdf_store=pdf_store,
    pdfbox_jar_path=PDF_BOX_EXEC,
Пример #23
0
cors = CORS(allow_origins_list=['*'],
            allow_all_methods=True,
            allow_all_origins=True,
            allow_all_headers=True)

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

#Create the app
app = falcon.API(middleware=[
    cors.middleware,
    auth_middleware,
    PeeweeConnectionMiddleware(),
    MultipartMiddleware(),
])

#Routes
app.add_route('/info', serverInfo())

app.add_route('/api/v1/accounts/{username}', getUser())
app.add_route('/api/v1/accounts/{username}/statuses', getStatuses())
app.add_route('/api/v1/accounts/{username}/followers', getFollowers())
app.add_route('/api/v1/statuses', manageUserStatuses())

app.add_route('/api/v1/auth/', authUser())

app.add_route('/api/v1/timelines/home', homeTimeline())

app.add_route('/api/v1/follows', followAction())
Пример #24
0
        annotation_count = (
            ProductInsight.select().where(ProductInsight.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()]
)

json_handler = falcon.media.JSONHandler(dumps=orjson.dumps, loads=orjson.loads)
extra_handlers = {
    "application/json": json_handler,
}

api.resp_options.media_handlers.update(extra_handlers)

# 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
# defines urls
api.add_route("/api/v1/insights/{barcode}", ProductInsightResource())
Пример #25
0
########################################################################################################################
# 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',
Пример #26
0
from buttons import MachinaCompiler, MachinaRunner, MachinaClean, MachinaStep
from lea import MachinaInput
from chmaquina_settings import MachinaSettings
import falcon, os, sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../src")
from scheduler import Scheduler
from falcon_multipart.middleware import MultipartMiddleware
from falcon_cors import CORS

cors = CORS(allow_origins_list=['*'],
            allow_all_origins=True,
            allow_all_headers=True,
            allow_all_methods=True)

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

ch = Scheduler()
# api.add_route('/api/leaCreateForm', MachinaInputCreate(ch))
api.add_route('/api/lea', MachinaInput(ch))
api.add_route('/api/compile', MachinaCompiler(ch))
api.add_route('/api/run', MachinaRunner(ch))
api.add_route('/api/nav', MachinaSettings(ch))
api.add_route('/api/clean', MachinaClean(ch))
api.add_route('/api/step', MachinaStep(ch))
Пример #27
0
args = utils.RegisterLaunchArguments()

cfgPath = args.cfgpath
profile = args.profile

# configure
with open(cfgPath) as f:
    cfg = utils.GetAuthProfile(json.load(f), profile, args)
    DBConnection.configure(**cfg['each_db'])
    if 'oidc' in cfg:
        cfg_oidc = cfg['oidc']

general_executor = ftr.ThreadPoolExecutor(max_workers=20)

# change line to enable OAuth autorization:
wsgi_app = api = falcon.API(middleware=[CORS(), Auth(), MultipartMiddleware()])
#wsgi_app = api = falcon.API(middleware=[CORS(), MultipartMiddleware()])

server = SpecServer(operation_handlers=operation_handlers)

if 'server_host' in cfg:
    with open('swagger.json') as f:
        swagger_json = json.loads(f.read(), object_pairs_hook=OrderedDict)

    server_host = cfg['server_host']
    swagger_json['host'] = server_host

    baseURL = '/each'
    if 'basePath' in swagger_json:
        baseURL = swagger_json['basePath']
Пример #28
0
from binascii import hexlify
from hashlib import md5
import os
import threading
import sys
import falcon
import vulnpy.falcon
import time

MIDDLEWARE = []
if os.environ.get("VULNPY_FALCON_MULTIPART_MIDDLEWARE"):
    from falcon_multipart.middleware import MultipartMiddleware

    MIDDLEWARE.append(MultipartMiddleware())


class Index(object):
    def on_get(self, req, resp):
        raise falcon.HTTPFound("/vulnpy")


class FileUpload(object):
    def on_post(self, req, resp):
        user_input = req._params["upload"].file.read()

        digest = hexlify(md5(user_input).digest()).decode("utf8")

        cmd = "echo " + str(user_input[:10])
        os.system(cmd)

        resp.status = falcon.HTTP_200
Пример #29
0
            stems = req.get_param('stems', '2')
            high_freq = req.get_param_as_bool('highFreq', default=True)

            t = pool.apply_async(Split.split,
                                 (file_path, stems, uuid, high_freq))
            add_task(uuid, t)

            resp.media = {'id': uuid}
            resp.status = falcon.HTTP_200


class Download(object):
    def on_get(self, req, resp, uuid):
        global OUTPUT_DIR
        zip_path = os.path.join(OUTPUT_DIR, f'{uuid}.zip')

        if not os.path.exists(zip_path):
            resp.status = falcon.HTTP_404
            return

        resp.status = falcon.HTTP_200
        resp.content_type = 'application/zip'
        with open(zip_path, 'rb') as f:
            resp.body = f.read()


api = falcon.API(middleware=[MultipartMiddleware()])
api.add_route('/status', Status())
api.add_route('/seperate', Seperate())
api.add_route('/download/{uuid}', Download())
Пример #30
0
        if filename.endswith('xlsx'):
            try:
                result = os.system(
                    '/home/eliot/anaconda2/bin/python A-B_cal.py -f ' +
                    filename + ' -g ' + gen + ' -t ' + t)
                with open('tmp.html', 'r') as f:
                    html = f.read()
                resp.content_type = "text/html"
                resp.set_header("Access-Control-Allow-Origin", "*")
                resp.set_header(
                    "Access-Control-Allow-Headers",
                    "Origin, X-Requested-With, Content-Type, Accept")
                resp.status = falcon.HTTP_200
                resp.body = html
            except:
                resp.body = "It have something wrong in your file format, please check it!!"

        else:
            resp.body = "Accept xlsx only!!, please check your file format."


api = application = falcon.API(middleware=[MultipartMiddleware()])
api.req_options.auto_parse_form_urlencoded = True
api.add_route('/', Resource())
api.add_route('/upload', UploadData())

#if __name__ == '__main__':
#    http = simple_server.make_server('192.168.5.82', 5001, app)
#    http.serve_forever()