Пример #1
0
    def init_app(self, app):
        """Initialize with app."""
        self._init_client_resources(app)

        prefix = app.config['API_URL_PREFIX']
        api = Api(self.api_blueprint, prefix=prefix)
        api.decorators = [cors.crossdomain(origin='*')]
        self._init_api_resources(api)

        app.register_blueprint(self.api_blueprint)
Пример #2
0
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@author: houxue
@date: 2017/5/22
"""
from flask_restful import Api
from flask_restful.utils import cors
from . import app

from api.resources.test import Hello

from api.resources.line import Line, LineHeat
from api.resources.tg import TgHeat, TgEq, TopTgHeat, TgInCircle, TgInBox
from api.resources.user import UserByType, UserInCircle, UserInBox, UserInShape, Cluster

api = Api(app)
api.decorators = [cors.crossdomain(origin='*')]

api.add_resource(Hello, '/hello')

api.add_resource(Line, '/line/query')
api.add_resource(LineHeat, '/line/heat')

api.add_resource(TgHeat, '/tg/heat')
api.add_resource(TgEq, '/tg/eq')
api.add_resource(TopTgHeat, '/tg/topTg')
api.add_resource(TgInCircle, '/tg/incircle')
api.add_resource(TgInBox, '/tg/inbox')

api.add_resource(UserByType, '/user/bytype')
api.add_resource(UserInCircle, '/user/incircle')
api.add_resource(UserInBox, '/user/inbox')
Пример #3
0
import os

from flask import Flask
from flask_restful import Resource, Api
from flask.ext.restful.utils import cors

from db import PostgreSQL

app = Flask(__name__)
api = Api(app)
api.decorators = [cors.crossdomain(
    origin="*", headers=['accept', 'Content-Type'],
    methods=['HEAD', 'OPTIONS', 'GET', 'PUT', 'POST', 'DELETE'])]

class BlastImage(Resource):

    def __init__(self):
        if 'BLAST_IMAGE_DB_SERVICE_HOST' in os.environ:
            self._db = PostgreSQL(os.environ['POSTGRESQL_USER'], \
                os.environ['POSTGRESQL_PASSWORD'], \
                os.environ['BLAST_IMAGE_DB_SERVICE_HOST'], \
                os.environ['BLAST_IMAGE_DB_SERVICE_PORT'])
        else:
            self._db = PostgreSQL('user', 'password', 'localhost', '5432')

    def get(self, tag):
        items = []
        for obj in self._db.get(tag):
            items.append({'tag': obj['tag'], 'image': obj['image']})
        return items
Пример #4
0
from flask import Flask
from flask_restful import Api
from flask_restful.utils import cors

import server.resources as Resources

APP = Flask(__name__)
API = Api(APP)

API.decorators = [cors.crossdomain(origin='*', headers=['accept', 'Content-Type'])] 


API.add_resource(Resources.Services, '/')
API.add_resource(Resources.ConvexHull, '/convexHull')

if __name__ == '__main__':
    APP.run(debug=True)
Пример #5
0
from flask_restful import Api, Resource, reqparse
from flask_restful.utils import cors
from flask_mongoengine import MongoEngine
from sentiment_scraper.models.article import Article

env = os.environ.get('NEWS_SENTIMENT_ENV', 'development')
if env == 'prod' or env == 'production':
    from server.config import ProdConfig as Config
else:
    from server.config import DevConfig as Config

app = Flask(__name__)
api = Api(app)
app.config.from_object(Config)
db = MongoEngine(app)
api.decorators = [cors.crossdomain(origin='*', headers=['Content-Type'])]


class SingleArticleRes(Resource):
    """

    """
    def get(self, id):
        response = {}
        article = Article.objects.get(id=id)
        article.load_text()
        response['result'] = article.to_json()
        return json.dumps(response), 200


class AllArticlesRes(Resource):
Пример #6
0
from flask_restful.utils import cors
from flask_paginate import Pagination
import random
from bson.son import SON
import os
import datetime
import calendar
from dateutil.parser import *

MONGOLAB_URL = os.environ['MONGOLAB_URL']
DEFAULT_HARVEST_DATE = datetime.datetime(2016, 1, 1, 0, 0, 0)

app = Flask(__name__)
api = Api(app)
api.decorators = [cors.crossdomain(
    origin='*',
    methods=['GET'],
)]

REASONS = {
    '33(1)(a)': {
        'definition':
        'contains information or matter the disclosure of which under this Act could reasonably be expected to cause damage to the security, defence or international relations of the Commonwealth',
        'source': 'act'
    },
    '33(1)(b)': {
        'definition':
        'contains information or matter: (i) that was communicated in confidence by, or on behalf of, a foreign government, an authority of a foreign government or an international organisation (the foreign entity) to the Government of the Commonwealth, to an authority of the Commonwealth or to a person who received the communication on behalf of the Commonwealth or an authority of the Commonwealth (the Commonwealth entity); and (ii) which the foreign entity advises the Commonwealth entity is still confidential; and (iii) the confidentiality of which it would be reasonable to maintain',
        'source': 'act'
    },
    '33(1)(c)': {
        'definition':
Пример #7
0
import serial
import time
import logging

import re
import glob

logging.basicConfig(level=logging.DEBUG,
					format='(%(threadName)-9s) %(message)s',)

app = Flask(__name__)
api = Api(app)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
api.decorators=[cross_origin()]
q = Queue()

grbl_in = Queue()
grbl_out = Queue()




# Open grbl serial port
s = serial.Serial(glob.glob('/dev/tty.usb*')[0],115200)
# /dev/ttyUSB0



Пример #8
0
from api.login import Login
from api.logout import Logout
from api.search import Search
from api.milestone import Milestone
from api.set_skills import SetSkills
from api.get_skills import GetSkills
from api.create_skill import CreateSkill
from api.guideline import Guideline
from api.remove_skill import RemoveSkill
from api.remove_milestone import RemoveMilestone

api = Api(app)
api.decorators = [
    cors.crossdomain(
        origin='*',
        headers=['accept', 'Content-Type', 'Access-Control-Allow-Origin'])
]
api.add_resource(Login, "/login")
api.add_resource(Logout, "/logout")
api.add_resource(Search, "/search")
api.add_resource(Milestone, "/milestone")
api.add_resource(SetSkills, "/setSkills")
api.add_resource(GetSkills, "/getSkills")
api.add_resource(CreateSkill, "/createSkill")
api.add_resource(Guideline, "/guideline")
api.add_resource(RemoveSkill, "/deleteSkill")
api.add_resource(RemoveMilestone, "/deleteMilestone")

if __name__ == "__main__":
    app.run(host="0.0.0.0")
Пример #9
0
from flask_restful import Api, Resource, reqparse
from flask_restful.utils import cors
from flask_mongoengine import MongoEngine
from sentiment_scraper.models.article import Article

env = os.environ.get('NEWS_SENTIMENT_ENV', 'development')
if env == 'prod' or env == 'production':
    from server.config import ProdConfig as Config
else:
    from server.config import DevConfig as Config

app = Flask(__name__)
api = Api(app)
app.config.from_object(Config)
db = MongoEngine(app)
api.decorators = [cors.crossdomain(origin='*', headers=['Content-Type'])]


class SingleArticleRes(Resource):
    """

    """
    def get(self, id):
        response = {}
        article = Article.objects.get(id=id)
        article.load_text()
        response['result'] = article.to_json()
        return json.dumps(response), 200


class AllArticlesRes(Resource):
Пример #10
0
app = Flask(__name__)
# app.wsgi_app = WhiteNoise(app.wsgi_app)
# app.wsgi_app.add_files('static/')
app.config['FLASKS3_BUCKET_NAME'] = 'yupikmodulesweb'
# app.config['FLASKS3_REGION'] = 'DEFAULT'
app.config['FLASKS3_DEBUG'] = True
app.config['FLASKS3_HEADERS'] = {
    'Cache-Control': 'max-age=86400',
}
app.config['FLASKS3_ONLY_MODIFIED'] = True
app.config['FLASKS3_GZIP'] = True
Compress(app)
s3 = FlaskS3(app)
api = Api(app)

api.decorators = [cors.crossdomain(origin='*', automatic_options=False)]
api.methods = ['GET', 'OPTIONS', 'POST', 'PUT']

# Define parser and request args
parser_api = reqparse.RequestParser()
parser_api.add_argument('root', type=str)
parser_api.add_argument('postbase', type=str, action='append')

# FIXME obsolete
# Takes a list of dict/json objects and add id field
# def index(l):
#     new_l = []
#     for i in range(len(l)):
#         new_x = l[i]
#         new_x['id'] = i
#         new_l.append(new_x)
Пример #11
0
    'lat': fields.Float,
    'lon': fields.Float,
    'radius': fields.Integer
}

action_fields = {
    'task': fields.String(attribute='task_id'),
    'timestamp': fields.DateTime,
    'status': fields.String,
    'user': fields.String(attribute='user_id')
}

user_summary = {'id': fields.Integer, 'display_name': fields.String}

api = Api(app)
api.decorators = [cors.crossdomain(origin=app.config['METRICS_URL'])]

# override the default JSON representation to support the geo objects


class ApiPing(Resource):
    """a simple ping endpoint"""
    def get(self):
        return ["I am alive"]


class ApiChallenge(Resource):
    @marshal_with(challenge_summary)
    def get(self):
        """Return a single challenge"""
        c = None
Пример #12
0
from flask_restful import Api

from app import app
from .infofill import UserView, RoleView, ActivateAccount, Authenticate, AttachUserRole
from flask_restful.utils import cors

app.secret_key = 'nexii'

restServerInstance = Api(app)
restServerInstance.decorators = [cors.crossdomain(origin='*')]

restServerInstance.add_resource(AttachUserRole,
                                "/api/v1.0/attach/user/role/",
                                endpoint="AttachUserRole")
restServerInstance.add_resource(UserView,
                                "/api/v1.0/user/",
                                endpoint="UserView")
restServerInstance.add_resource(RoleView,
                                "/api/v1.0/role/",
                                endpoint="RoleView")
restServerInstance.add_resource(ActivateAccount,
                                "/api/v1.0/activate/",
                                endpoint="activate_account")
restServerInstance.add_resource(Authenticate,
                                "/api/v1.0/auth/signin/",
                                endpoint="Authenticate")
Пример #13
0
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 14 18:47:34 2020

@author: Demo
"""
from flask import Flask, request, jsonify, current_app
from flask_sqlalchemy import SQLAlchemy
from flask_restful import Api, Resource
from flask_restful.utils import cors
from flask_ormapi_factory import ModelFactory, ResourceFactory, create_token, login_required
app = Flask(__name__)
app.secret_key = '123'

api = Api(app)
api.decorators = [cors.crossdomain(origin='*',\
    headers=['accept', 'Content-Type','Authorization'],methods={"HEAD","POST","GET",'OPTIONS','PUT','DELETE'})] ## 支持跨域

# 配置SQLALCHEMY
app.config[
    'SQLALCHEMY_DATABASE_URI'] = "postgresql://*****:*****@127.0.0.1/test"
app.config['SQLALCHEMY_COMMIT_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
db = SQLAlchemy(app)
model_factory = ModelFactory(app)
resource_factory = ResourceFactory(app)


class BaseResource(Resource):
    def options(self):
        return 'ok'
Пример #14
0
from flask import Blueprint
from flask_restful import Api, Resource, url_for
from flask_restful.utils import cors

api_bp = Blueprint('api', __name__)
api = Api(api_bp)
api.decorators = [cors.crossdomain(origin='*', headers=['accept', 'Content-Type','Authorization'])]

from . import routes
Пример #15
0
from flask_restful import fields, marshal_with, reqparse, inputs
from flask.ext.restful.utils import cors
from flask.ext.paginate import Pagination
import random
from bson.son import SON
import os
import datetime
from dateutil.parser import *


MONGOLAB_URL = os.environ['MONGOLAB_URL']
DEFAULT_HARVEST_DATE = datetime.datetime(2016, 1, 1, 0, 0, 0)

app = Flask(__name__)
api = Api(app)
api.decorators = [cors.crossdomain(origin='*', methods=['GET'],)]

REASONS = {
    '33(1)(a)': {'definition': 'contains information or matter the disclosure of which under this Act could reasonably be expected to cause damage to the security, defence or international relations of the Commonwealth', 'source': 'act'},
    '33(1)(b)': {'definition':  'contains information or matter: (i) that was communicated in confidence by, or on behalf of, a foreign government, an authority of a foreign government or an international organisation (the foreign entity) to the Government of the Commonwealth, to an authority of the Commonwealth or to a person who received the communication on behalf of the Commonwealth or an authority of the Commonwealth (the Commonwealth entity); and (ii) which the foreign entity advises the Commonwealth entity is still confidential; and (iii) the confidentiality of which it would be reasonable to maintain', 'source': 'act'},
    '33(1)(c)': {'definition': 'contains information or matter the disclosure of which under this Act would have a substantial adverse effect on the financial or property interests of the Commonwealth or of a Commonwealth institution and would not, on balance, be in the public interest', 'source': 'act'},
    '33(1)(d)': {'definition': 'contains information or matter the disclosure of which under this Act would constitute a breach of confidence', 'source': 'act'},
    '33(1)(e)(i)': {'definition': 'contains information or matter the disclosure of which under this Act would, or could reasonably be expected to prejudice the conduct of an investigation of a breach, or possible breach, of the law, or a failure, or possible failure, to comply with a law relating to taxation or prejudice the enforcement or proper administration of the law in a particular instance', 'source': 'act'},
    '33(1)(e)(ii)': {'definition': 'contains information or matter the disclosure of which under this Act would, or could reasonably be expected to disclose, or enable a person to ascertain, the existence or identity of a confidential source of information in relation to the enforcement or administration of the law', 'source': 'act'},
    '33(1)(e)(iii)': {'definition': 'contains information or matter the disclosure of which under this Act would, or could reasonably be expected to endanger the life or physical safety of any person', 'source': 'act'},
    '33(1)(f)(ii)': {'definition': 'contains information or matter the disclosure of which under this Act would, or could reasonably be expected to disclose lawful methods or procedures for preventing, detecting, investigating, or dealing with matters arising out of, breaches or evasions of the law the disclosure of which would, or would be reasonably likely to, prejudice the effectiveness of those methods or procedures', 'source': 'act'},
    '33(1)(f)(iii)': {'definition': 'contains information or matter the disclosure of which under this Act would, or could reasonably be expected to prejudice the maintenance or enforcement of lawful methods for the protection of public safety', 'source': 'act'},
    '33(1)(g)': {'definition': 'contains information or matter the disclosure of which under this Act would involve the unreasonable disclosure of information relating to the personal affairs of any person (including a deceased person)', 'source': 'act'},
    '33(1)(h)': {'definition': 'contains information or matter relating to trade secrets, or any other information or matter having a commercial value that would be, or could reasonably be expected to be, destroyed or diminished if the information or matter were disclosed', 'source': 'act'},
    '33(1)(j)': {'definition': 'contains information or matter (other than information or matter referred to in paragraph (h)) concerning a person in respect of his or her business or professional affairs or concerning the business, commercial or financial affairs of an organization or undertaking, being information or matter the disclosure of which would, or could reasonably be expected to, unreasonably affect that person adversely in respect of his or her lawful business or professional affairs or that organization or undertaking in respect of its lawful business, commercial or financial affairs', 'source': 'act'},
    '33(2)(a)': {'definition': 'of such a nature that it would be privileged from production in legal proceedings on the ground of legal professional privilege', 'source': 'act'},
Пример #16
0
from flask_restful.utils import cors
from resources.nfl.player import NFL_Player_2015, All_NFL_Players_2015
from resources.nfl.team import NFL_Teams_2015, NFL_Team_2015
import resources.nfl.totals as t
import resources.nfl.games as g
import resources.nfl.trending as trend



from models.nfl_qb_game_2015 import NFL_QB_Game_2015_M
from models.nfl_rb_game_2015 import NFL_RB_Game_2015_M
from models.nfl_wr_game_2015 import NFL_WR_Game_2015_M
from models.nfl_te_game_2015 import NFL_TE_Game_2015_M


api = Api(app)
api.decorators = [cors.crossdomain(origin='*')]

# Public APIS

api.add_resource(NFL_Teams_2015, '/api/nfl/teams')
api.add_resource(NFL_Player_2015, '/api/nfl/player/<int:player_id>', endpoint='player_id')
api.add_resource(NFL_Team_2015, '/api/nfl/team/<int:team_id>', endpoint='team_id')

# Private APIS

api.add_resource(All_NFL_Players_2015, '/api/nfl/players')
api.add_resource(t.Pos_Totals_2015, '/api/nfl/totals/<string:pos>')
api.add_resource(g.Pos_Games_2015, '/api/nfl/games/<string:pos>')
api.add_resource(trend.Trending_Players, '/api/nfl/trending')
Пример #17
0
import os
import sys

from flask import Flask
from flask_restful import Resource, Api
from flask_restful.utils import cors

from db import Mongo

app = Flask(__name__)
api = Api(app)
api.decorators = [
    cors.crossdomain(
        origin="*",
        headers=['accept', 'Content-Type'],
        methods=['HEAD', 'OPTIONS', 'GET', 'PUT', 'POST', 'DELETE'])
]


class BlastText(Resource):
    def __init__(self):
        if 'TEXT_DB_SERVICE_HOST' in os.environ:
            self.db = Mongo(os.getenv('MONGODB_USER'), \
                os.getenv('MONGODB_PASSWORD'), \
                os.getenv('TEXT_DB_SERVICE_HOST'), \
                os.getenv('TEXT_DB_SERVICE_PORT'))
        else:
            self.db = Mongo('user', 'password', 'localhost', '27017')

    def get(self, text):
        items = []
Пример #18
0
from flask import Flask
from flask_restful import Api
from flask_restful.utils import cors
from api.name import NameAPI

app = Flask(__name__)
api = Api(app)
api.decorators = [
    cors.crossdomain(origin='*',
                     headers='my-header, accept, content-type, token')
]

api.add_resource(NameAPI, '/name')

if __name__ == '__main__':
    app.run(debug=True)
Пример #19
0
}

action_fields = {
    'task': fields.String(attribute='task_id'),
    'timestamp': fields.DateTime,
    'status': fields.String,
    'user': fields.String(attribute='user_id')
}

user_summary = {
    'id': fields.Integer,
    'display_name': fields.String
}

api = Api(app)
api.decorators = [cors.crossdomain(origin=app.config['METRICS_URL'])]

# override the default JSON representation to support the geo objects


class ApiPing(Resource):

    """a simple ping endpoint"""

    def get(self):
        return ["I am alive"]


class ApiChallenge(Resource):

    @marshal_with(challenge_summary)
Пример #20
0
def load_api(app):
    apis = Api(app)
    apis.decorators = [cors.crossdomain(origin='*')]
    apis.add_resource(Login, '/login')
    apis.add_resource(Reg, '/register')