def add_routes(app):
"""Add the routes to an app"""
for (prefix, routes) in API_SECTIONS:
api = Api(app, prefix=prefix)
for ((pattern, resource, *args), kwargs) in routes:
kwargs.setdefault('strict_slashes', False)
api.add_resource(resource, pattern, *args, **kwargs)
python类Api()的实例源码
def __init__(self, app, server):
# NetServer
self.server = server
# Set the version
self.version = 1.0
# Initialise the API
self.api = Api(app, prefix='/api/v' + str(self.version))
# Setup routing
self.resources = {
# System endpoint
'/system': RestSystem,
# Device endpoints
'/device/<int:deveui>': RestDevice,
'/devices': RestDevices,
# Application endpoints
'/app/<int:appeui>': RestApplication,
'/apps': RestApplications,
# Gateway endpoints
'/gateway/<host>': RestGateway,
'/gateways': RestGateways,
# Application interface endpoints
'/interface/<appinterface_id>': RestAppInterface,
'/interfaces': RestAppInterfaces,
# Application property endpoints
'/property/<int:appeui>': RestAppProperty,
'/propertys': RestAppPropertys
}
kwargs = {'restapi': self, 'server': self.server}
for path,klass in self.resources.iteritems():
self.api.add_resource(klass, path, resource_class_kwargs=kwargs)
def create_app():
_app = Flask(__name__)
# used for encrypting cookies for handling sessions
_app.config['SECRET_KEY'] = 'abc492ee-9739-11e6-a174-07f6b92d4a4b'
message_queue_type = environ.env.config.get(ConfigKeys.TYPE, domain=ConfigKeys.QUEUE, default=None)
if message_queue_type is None and not (len(environ.env.config) == 0 or environ.env.config.get(ConfigKeys.TESTING)):
raise RuntimeError('no message queue type specified')
message_queue = 'redis://%s' % environ.env.config.get(ConfigKeys.HOST, domain=ConfigKeys.CACHE_SERVICE, default='')
message_channel = 'dino_%s' % environ.env.config.get(ConfigKeys.ENVIRONMENT, default='test')
logger.info('message_queue: %s' % message_queue)
_api = Api(_app)
_socketio = SocketIO(
_app,
logger=logger,
engineio_logger=os.environ.get('DINO_DEBUG', '0') == '1',
async_mode='eventlet',
message_queue=message_queue,
channel=message_channel)
# preferably "emit" should be set during env creation, but the socketio object is not created until after env is
environ.env.out_of_scope_emit = _socketio.emit
_app.wsgi_app = ProxyFix(_app.wsgi_app)
return _app, _api, _socketio
def __init__(self,
app,
name=None,
version=None,
media_type=None,
**kwargs):
super().__init__(app=app, default_mediatype=media_type or self.MEDIA_TYPE, **kwargs)
@app.route('/')
def main():
return jsonify({
'name': name or 'Peach Rest Api',
'version': version or '0.0.0',
})
def init_app(self, app):
api = Api(app)
def create_api(app):
api = Api(app, catch_all_404s=True, errors=errors)
api.representations['application/xml'] = output_xml
got_request_exception.connect(log_exception, app)
api.add_resource(Recipes, '/recipes', endpoint='recipes')
api.add_resource(Recipes, '/recipes/<int:recipe_id>', endpoint='recipe')
def setup_api():
api = Api(app)
api.add_resource(ReadViaImage, ROOT_PATH + '/image')
api.add_resource(ReadViaUrl, ROOT_PATH + '/url')
def __init__(self, app):
QtCore.QThread.__init__(self)
self.app = app
self.flask_app = Flask(app.name, template_folder=sibling_path(__file__, 'templates'), )
self.flask_app.route('/')(self.index)
self.rest_api = Api(self.flask_app)
self.flask_app.config['RESTFUL_JSON'] = dict(indent=4)
self.rest_api.add_resource(MicroscopeRestResource,
'/api/app',
resource_class_kwargs={ 'microscope_app': self.app })
self.rest_api.add_resource(HardwareSettingsListRestResource,
'/api/hardware/<string:hw_name>/settings',
resource_class_kwargs={ 'microscope_app': self.app })
self.rest_api.add_resource(HardwareSettingsLQRestResource,
'/api/hardware/<string:hw_name>/settings/<string:lq_name>',
resource_class_kwargs={ 'microscope_app': self.app })
self.rest_api.add_resource(MeasurementSettingsListRestResource,
'/api/measurements/<string:measure_name>/settings',
resource_class_kwargs={ 'microscope_app': self.app })
self.rest_api.add_resource(MeasurementSettingsLQRestResource,
'/api/measurements/<string:measure_name>/settings/<string:lq_name>',
resource_class_kwargs={ 'microscope_app': self.app })
for HW in self.app.hardware.values():
#print(HW.web_ui())
self.flask_app.route('/hw/{}'.format(HW.name))(HW.web_ui)
for M in self.app.measurements.values():
self.flask_app.route('/measure/{}'.format(M.name))(M.web_ui)
def main():
app = Flask(__name__)
api = Api(app)
# localhost:5000/
APIRoot.register_root(api)
# localhost:5000/api/
#APIRoot.register_root(api, root='/api')
app.run()
flask_restful_wrapper.py 文件源码
项目:opserv-backend
作者: OpServ-Monitoring
项目源码
文件源码
阅读 19
收藏 0
点赞 0
评论 0
def __init__(self, app):
self.__api = Api(app)
# enable basic auth if a password is set
password = AppSettings.get_setting(AppSettings.KEY_PASSWORD)
if password is not None:
app.config['BASIC_AUTH_USERNAME'] = 'opserv'
app.config['BASIC_AUTH_PASSWORD'] = password
self.__basic_auth = BasicAuth(app)
def __init__(self, host, http_port, ws_port,
ws_poll_interval, dring, verbose):
self.host = host
self.http_port = http_port
self.ws_port = ws_port
self.ws_poll_interval = ws_poll_interval
self.dring = dring
self.verbose = verbose
# Flask Application
self.app = Flask(__name__)
self.app.config['SECRET_KEY'] = 't0p_s3cr3t'
self.app.config.update(PROPAGATE_EXCEPTIONS=True)
# Flask Restuful API
self.api = Api(
app=self.api_blueprint,
prefix=self.API_URL_PREFIX,
catch_all_404s=True
)
# Cross Origin Resource Sharing is needed to define response headers
# to allow HTTP methods from in-browser Javascript because accessing
# a different port is considered as accessing a different domain
self.api.decorators = [
cors.crossdomain(
origin='*',
methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS'],
attach_to_all=True,
automatic_options=True
)
]
self._init_api_resources()
self.app.register_blueprint(self.api_blueprint)
# Websockets
self._init_websockets()
self._register_callbacks()
def __init__(self):
self.logger = Logger.Logger('DevicePool')
self.__detectDevices()
self.service = Flask('DevicePool')
self.api = Api(self.service)
got_request_exception.connect(logException, self.service)
self.api.add_resource(Devices.DeviceIndex, '/devices/')
self.api.add_resource(Deploy.DeployIndex, '/deploy')
self.service.run(host='0.0.0.0', port=7890)
def __init__(self, rest_api, cors_domain_list=None, web_ui=False, eth_rpc_endpoint=None):
if rest_api.version != 1:
raise ValueError(
'Invalid api version: {}'.format(rest_api.version)
)
flask_app = Flask(__name__)
if cors_domain_list:
CORS(flask_app, origins=cors_domain_list)
if eth_rpc_endpoint:
if not eth_rpc_endpoint.startswith('http'):
eth_rpc_endpoint = 'http://{}'.format(eth_rpc_endpoint)
flask_app.config['WEB3_ENDPOINT'] = eth_rpc_endpoint
blueprint = create_blueprint()
flask_api_context = Api(blueprint, prefix=self._api_prefix)
restapi_setup_type_converters(
flask_app,
{'hexaddress': HexAddressConverter},
)
restapi_setup_urls(
flask_api_context,
rest_api,
URLS_V1,
)
self.rest_api = rest_api
self.flask_app = flask_app
self.blueprint = blueprint
self.flask_api_context = flask_api_context
self.wsgiserver = None
self.flask_app.register_blueprint(self.blueprint)
self.flask_app.config['WEBUI_PATH'] = '../ui/web/dist/'
if is_frozen():
# Inside frozen pyinstaller image
self.flask_app.config['WEBUI_PATH'] = '{}/raiden/ui/web/dist/'.format(sys.prefix)
if web_ui:
for route in ('/ui/<path:file>', '/ui', '/ui/', '/index.html', '/'):
self.flask_app.add_url_rule(
route,
route,
view_func=self._serve_webui,
methods=('GET', ),
)
def __init__(self, listenip, port, DCnetwork=None):
self.ip = listenip
self.port = port
# connect this DC network to the rest api endpoint (needed for the networking and monitoring api)
self.connectDCNetwork(DCnetwork)
# setup Flask
# find directory of dashboard files
dashboard_file = pkg_resources.resource_filename('emuvim.dashboard', "index.html")
dashboard_dir = path.dirname(dashboard_file)
logging.info("Started emu dashboard: {0}".format(dashboard_dir))
self.app = Flask(__name__, static_folder=dashboard_dir, static_url_path='/dashboard')
self.api = Api(self.app)
# setup endpoints
# compute related actions (start/stop VNFs, get info)
self.api.add_resource(Compute, "/restapi/compute/<dc_label>/<compute_name>")
self.api.add_resource(ComputeList,
"/restapi/compute",
"/restapi/compute/<dc_label>")
self.api.add_resource(ComputeResources, "/restapi/compute/resources/<dc_label>/<compute_name>")
self.api.add_resource(DatacenterStatus, "/restapi/datacenter/<dc_label>")
self.api.add_resource(DatacenterList, "/restapi/datacenter")
# network related actions (setup chaining between VNFs)
self.api.add_resource(NetworkAction,
"/restapi/network")
self.api.add_resource(NetworkLAN,
"/restapi/networkLAN")
self.api.add_resource(DrawD3jsgraph,
"/restapi/network/d3jsgraph")
# monitoring related actions
# export a network interface traffic rate counter
self.api.add_resource(MonitorInterfaceAction,
"/restapi/monitor/interface")
# export flow traffic counter, of a manually pre-installed flow entry, specified by its cookie
self.api.add_resource(MonitorFlowAction,
"/restapi/monitor/flow")
# install monitoring of a specific flow on a pre-existing link in the service.
# the traffic counters of the newly installed monitor flow are exported
self.api.add_resource(MonitorLinkAction,
"/restapi/monitor/link")
# install skewness monitor of resource usage disribution
# the skewness metric is exported
self.api.add_resource(MonitorSkewAction,
"/restapi/monitor/skewness")
# start a terminal window for the specified vnfs
self.api.add_resource(MonitorTerminal,
"/restapi/monitor/term")
logging.debug("Created API endpoint %s(%s:%d)" % (self.__class__.__name__, self.ip, self.port))
def create_app(taskflow_instance, connection_string=None, secret_key=None):
app = flask.Flask(__name__)
app.config['DEBUG'] = os.getenv('DEBUG', False)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = connection_string or os.getenv('SQL_ALCHEMY_CONNECTION')
app.config['SESSION_COOKIE_NAME'] = 'taskflowsession'
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['PERMANENT_SESSION_LIFETIME'] = 43200
app.config['SECRET_KEY'] = secret_key or os.getenv('FLASK_SESSION_SECRET_KEY')
db = SQLAlchemy(metadata=metadata, model_class=BaseModel)
db.init_app(app)
api = Api(app)
CORS(app, supports_credentials=True)
login_manager = LoginManager()
login_manager.init_app(app)
@login_manager.user_loader
def load_user(user_id):
return db.session.query(User).filter(User.id == user_id).first()
def apply_attrs(class_def, attrs):
for key, value in attrs.items():
setattr(class_def, key, value)
return class_def
attrs = {
'session': db.session,
'taskflow': taskflow_instance
}
with app.app_context():
api.add_resource(apply_attrs(resources.LocalSessionResource, attrs), '/v1/session')
api.add_resource(apply_attrs(resources.WorkflowListResource, attrs), '/v1/workflows')
api.add_resource(apply_attrs(resources.WorkflowResource, attrs), '/v1/workflows/<workflow_name>')
api.add_resource(apply_attrs(resources.TaskListResource, attrs), '/v1/tasks')
api.add_resource(apply_attrs(resources.TaskResource, attrs), '/v1/tasks/<task_name>')
api.add_resource(apply_attrs(resources.WorkflowInstanceListResource, attrs), '/v1/workflow-instances')
api.add_resource(apply_attrs(resources.WorkflowInstanceResource, attrs), '/v1/workflow-instances/<int:instance_id>')
api.add_resource(apply_attrs(resources.RecurringWorkflowLastestResource, attrs), '/v1/workflow-instances/recurring-latest')
api.add_resource(apply_attrs(resources.TaskInstanceListResource, attrs), '/v1/task-instances')
api.add_resource(apply_attrs(resources.TaskInstanceResource, attrs), '/v1/task-instances/<int:instance_id>')
api.add_resource(apply_attrs(resources.RecurringTaskLastestResource, attrs), '/v1/task-instances/recurring-latest')
return app
def get(self):
stock_date_range_parser.add_argument('params')
args = stock_date_range_parser.parse_args()
calcs = json.loads(args['params'])
x = get_series(args['symbol'], args['start'], args['end'])
#x.run_calculations()
cc = []
for calc in calcs:
t = calc['type']
p = calc['param']
if t == 'mavg':
cc.append(x.calculate_mavg(p['window']))
elif t == 'rsi':
cc.append(x.calculate_rsi(p['window']))
elif t == 'macd':
cc.append('signal_' + str(p['signal']))
cc.append(x.calculate_macd(**p))
elif t == '':
pass
#TODO
#x.calculate_mom()
#x.calculate_rocr()
#x.calculate_atr()
#x.calculate_mfi()
#x.calculate_obv()
#x.calculate_cci()
#x.calculate_trix()
#x.calculate_adx()
x.df = x.df.where((pd.notnull(x.df)), None) # cast Nan to Null
jret = {
'ohlc' : list(zip(x.df.epoch, x.df['Open'], x.df['High'], x.df['Low'], x.df['Adj_Close'])),
'volume': list(zip(x.df.epoch, x.df['Volume'])),
'columns': cc,
'backtesting': get_backtesting(args['start'], args['end'], x)
}
for c in cc:
jret[c] = list(zip(x.df.epoch, x.df[c]))
return jret
#
# Actually setup the Api resource routing here
#
def create_app():
app = Flask(__name__)
app.config.from_object(os.environ['APP_SETTINGS'])
from db import db
db.init_app(app)
# TODO: upload image
api = Api(app)
jwt = JWT(app, authenticate, identity) # endpoint '/auth'
# users
api.add_resource(UserRegister, '/v1/register')
api.add_resource(User, '/v1/users/<string:username>')
api.add_resource(UserId, '/v1/users/<int:user_id>')
# badges
api.add_resource(BadgeList, '/v1/users/<int:student_id>/badges')
api.add_resource(Badge, '/v1/users/<int:student_id>/badges/<int:badge_id>')
# categories
api.add_resource(CategoryList, '/v1/categories')
api.add_resource(Category, '/v1/categories/<int:category_id>')
# courses
api.add_resource(CourseList, '/v1/courses')
api.add_resource(Course, '/v1/courses/<int:course_id>')
api.add_resource(CourseRegister, '/v1/courses/<int:course_id>/users/<int:student_id>/register')
# chapters
api.add_resource(ChapterList, '/v1/courses/<int:course_id>/chapters')
api.add_resource(Chapter, '/v1/courses/<int:course_id>/chapters/<int:chapter_id>')
# quizzes
api.add_resource(QuizList, '/v1/courses/<int:course_id>/quizzes')
api.add_resource(Quiz, '/v1/courses/<int:course_id>/quizzes/<int:quiz_id>')
# comments
api.add_resource(CommentList, '/v1/courses/<int:course_id>/comments')
api.add_resource(Comment, '/v1/courses/<int:course_id>/comments/<int:comment_id>')
# ratings
api.add_resource(RatingList, '/v1/courses/<int:course_id>/ratings')
api.add_resource(Rating, '/v1/courses/<int:course_id>/ratings/<int:rating_id>')
# questions
api.add_resource(QuestionList, '/v1/quizzes/<int:quiz_id>/questions')
api.add_resource(Question, '/v1/quizzes/<int:quiz_id>/questions/<int:question_id>')
# answers
api.add_resource(AnswerList, '/v1/questions/<int:question_id>/answers')
api.add_resource(Answer, '/v1/questions/<int:question_id>/answers/<int:answer_id>')
# scores
api.add_resource(ScoreList, '/v1/quizzes/<int:quiz_id>/scores')
api.add_resource(Score, '/v1/quizzes/<int:quiz_id>/scores/<int:score_id>')
# steps
api.add_resource(Step, '/v1/users/<int:student_id>/courses/<int:course_id>/steps/<int:step_id>')
return app