Пример #1
0
class EffectAPI(Resource):
    reqparse = reqparse.RequestParser()
    reqparse.add_argument('kind', type=str, location='json')
    reqparse.add_argument('name', type=str, location='json')

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

    def get(self, pk):
        queryset = [effect for effect in effect_list if effect['pk'] == pk]
        if len(queryset) == 0:
            abort(404)
        return {'effect': marshal(queryset[0], effect_fields)}

    def delete(self, pk):
        queryset = [effect for effect in effect_list if effect['pk'] == pk]
        if len(queryset) == 0:
            abort(404)
        effect_list.remove(queryset[0])
        return {'result': True}, 204

    def put(self, pk):
        queryset = [effect for effect in effect_list if effect['pk'] == pk]
        if len(queryset) == 0:
            abort(404)
        effect = queryset[0]
        args = EffectAPI.reqparse.parse_args()
        for k, v in args.items():
            if v is not None:
                effect[k] = v
        return {'effect': marshal(effect, effect_fields)}, 201
Пример #2
0
 def post(self):
     parser.add_argument('sync')
     args = parser.parse_args(req=request)
     if args['sync'] == '':
         stock_tushare.sync_daily()
     elif args['sync'] == '':
         stock_tushare.sync_week()
     else:
         return {'result': -1, 'message': '参数错误'}
     return {'result': 0, 'message': ''}
Пример #3
0
def endpoint_config():
    reqparse.add_argument('model_endpoint', type=str, required=True)
    args = reqparse.parse_args()
    resp = sagemaker.predict(args.model_endpoint, {
        'text': 'this is just a test',
        'include_run_config': True
    })
    status_code = resp['ResponseMetadata']['HTTPStatusCode']
    if status_code != 200:
        logger.error(resp)
        return error_response(status_code,
                              'Getting config unsuccessful.',
                              error_type=resp['Error']['Code'])
    prediction = json.loads(resp['Body'].read())
    config = prediction['run_config']
    return jsonify(config)
Пример #4
0
def endpoint_labels():
    reqparse.add_argument('model_endpoint', type=str, required=True)
    args = reqparse.parse_args()
    resp = sagemaker.predict(args.model_endpoint,
                             {'text': 'this is just a test'})
    status_code = resp['ResponseMetadata']['HTTPStatusCode']
    if status_code != 200:
        logger.error(resp)
        return error_response(status_code,
                              'Getting endpoint labels unsuccessful.',
                              error_type=resp['Error']['Code'])
    prediction = json.loads(resp['Body'].read())
    labels = prediction['predictions'][0]['labels_fixed']
    label_vals = Predict.labels_to_int(labels)
    label_obj = {'labels': labels}
    if label_vals is not None:
        label_obj = {**label_obj, 'label_vals': label_vals}
    return jsonify(label_obj)
Пример #5
0
 def __init__(self):
     self.reqpare = reqparse.RequestParser()
     self.reqpare.add_argument('course',
                               type=inputs.positive,
                               required=True,
                               help='No Course Provider',
                               location=['json', 'form'])
     self.reqpare.add_argument('rating',
                               type=inputs.int_range(1, 5),
                               required=True,
                               help='No rating Provided',
                               location=['json', 'form'])
     self.reqpare = reqparse.add_argument('comment',
                                          required=False,
                                          nullable=True,
                                          location=['json', 'form'],
                                          default='')
     super().__init__()
Пример #6
0
def predict():
    reqparse.add_argument('text', type=str, required=True)
    reqparse.add_argument('model_endpoint', type=str, required=True)
    reqparse.add_argument('project', type=str, required=False)
    args = reqparse.parse_args()
    resp = sagemaker.predict(args.model_endpoint, {'text': args.text})
    status_code = resp['ResponseMetadata']['HTTPStatusCode']
    if status_code != 200:
        logger.error(resp)
        return error_response(status_code,
                              'Prediction unsuccessful.',
                              error_type=resp['Error']['Code'])
    prediction = json.loads(resp['Body'].read())
    return jsonify(prediction)
Пример #7
0
from flask_restful import reqparse, Resource, fields, abort, marshal_with

from app import db
from app.models import SKU
from app.resources import non_empty_string

sku_fields = {
    'id': fields.Integer,
    'name': fields.String,
}

reqparse = reqparse.RequestParser()
reqparse.add_argument('name',
                      type=non_empty_string,
                      required=True,
                      help='No product name provided',
                      location='json')


class SKUList(Resource):
    @marshal_with(sku_fields)
    def get(self):
        return SKU.query.all()

    @marshal_with(sku_fields)
    def post(self):
        parsed_args = reqparse.parse_args()
        sku = SKU(name=parsed_args['name'])
        db.session.add(sku)
        db.session.commit()
        return sku, 201
Пример #8
0
from flask_restful import Resource, reqparse
import json
import os

api_version = 'v1'
configmap_file = '/tmp/configmap.json'

reqparse = reqparse.RequestParser()
reqparse.add_argument('auth_type',
                      type=str,
                      required=False,
                      help="No authentication type provided")
reqparse.add_argument('workshop_name',
                      type=str,
                      required=False,
                      help="No workshop type specified")


class ConfigMapAPI(Resource):
    """Gets and existing ConfigMap object or generates a new one, depending on the HTTP Type"""
    def get(self):
        """Retrieves an existing ConfigMap object"""
        if os.path.exists(configmap_file):
            with open(configmap_file, 'r') as configmap_data:
                return json.load(configmap_data)

        else:
            return {'configmap': 'No ConfigMap present'}, 400

    def post(self):
        """Creates a new ConfigMap"""
Пример #9
0
from flask_restful import reqparse, Resource, fields, abort, marshal_with

from app import db
from app.models import Order
from app.resources import non_empty_string
from app.utils import normalizer

order_fields = {'id': fields.Integer, 'customer': fields.String}

reqparse = reqparse.RequestParser()
reqparse.add_argument('customer',
                      type=non_empty_string,
                      required=True,
                      help='No customer name provided',
                      location='json')


class OrderList(Resource):
    @marshal_with(order_fields)
    def get(self):
        return Order.query.all()

    @marshal_with(order_fields)
    def post(self):
        parsed_args = reqparse.parse_args()
        order = Order(customer=parsed_args['customer'])
        order.normalized = normalizer(order.customer)
        db.session.add(order)
        db.session.commit()
        return order, 201
Пример #10
0
#
# Created by OFShare on 2020-03-27
#

import datetime
from flask import Flask
from flask_restful import Api, Resource, reqparse

app = Flask(__name__)
api = Api(app)

reqparse = reqparse.RequestParser()
reqparse.add_argument('name', type=str, required=True, location='form')


class HelloWorld(Resource):
    def get(self):
        print("receive get...")
        return {'hello': 'world'}

    def post(self):
        print("receive post...")
        args = reqparse.parse_args()
        name = args['name']
        return "hello " + name + " " + str(datetime.date.today())


api.add_resource(HelloWorld, '/')

if __name__ == '__main__':
    app.run(debug=True, port=8123)
Пример #11
0
    @staticmethod
    def verify_hash(password, hash):
        return sha256.verify(password, hash)


user_fields = {
    'email': fields.String,
    'phone_number': fields.Integer,
    'username': fields.String,
    'password': fields.String
}

reqparse = reqparse.RequestParser()
reqparse.add_argument('email',
                      type=str,
                      required=True,
                      help='please input email',
                      location='json')
reqparse.add_argument('phone_number',
                      type=str,
                      required=True,
                      help='please input phone_No',
                      location='json')
reqparse.add_argument('username',
                      type=str,
                      required=True,
                      help='please input username',
                      location='json')
reqparse.add_argument('password',
                      type=str,
                      required=True,
Пример #12
0
from flask_restful import reqparse, Resource, fields, abort, marshal_with

from app import db
from app.models import SKU, Storage

storage_fields = {
    'id': fields.Integer,
    'quantity': fields.Integer(attribute=lambda x: x.stock),
    'sku': fields.String(attribute=lambda x: x.sku.name)
}

reqparse = reqparse.RequestParser()
reqparse.add_argument('quantity',
                      type=int,
                      required=True,
                      help='No stock amount provided (quantity)',
                      location='json')
reqparse.add_argument('sku',
                      type=str,
                      required=True,
                      help='No product provided',
                      location='json')


class StorageList(Resource):
    @marshal_with(storage_fields)
    def get(self):
        return Storage.query.all()

    @marshal_with(storage_fields)
    def post(self):
Пример #13
0
    def __str__(self):
        return self.title


resource_fields = {
    'username': fields.String,
    'title': fields.String,
    'description': fields.String,
    'category': fields.String
}

reqparse = reqparse.RequestParser()
reqparse.add_argument('title',
                      type=str,
                      required=True,
                      help='No request title provided',
                      location='json')
reqparse.add_argument('description',
                      type=str,
                      required=True,
                      help='No request description provided',
                      location='json')
reqparse.add_argument('category',
                      type=str,
                      required=True,
                      help='Choose category',
                      location='json')
reqparse_copy = reqparse.copy()
reqparse_copy.add_argument('title', type=str, required=False, location='json')
reqparse_copy.add_argument('description',
Пример #14
0
def delete_model():
    reqparse.add_argument('model_name', type=str, required=True)
    args = reqparse.parse_args()
    resp = sagemaker.delete_model(model_name=args.model_name)
    return success_response(200, 'Successfully created endpoint.')
Пример #15
0
def list_endpoints():
    reqparse.add_argument('active', type=bool, required=False, default=False)
    args = reqparse.parse_args()
    endpoints = sagemaker.list_endpoints(active=args.active)
    return jsonify(endpoints)
Пример #16
0
        return sha256.hash (password)

    @staticmethod
    def verify_hash(password,hash):
        return sha256.verify(password,hash)


user_fields = {
    'email': fields.String,
    'username': fields.String,
    'password': fields.String,
}


reqparse = reqparse.RequestParser()
reqparse.add_argument('username', type=str, required=True, help='please choose username', location='json')
reqparse.add_argument('email', type=str, required=True, help='No user email provided', location='json')
reqparse.add_argument('password', type=str, required=True, help='include password', location='json')

reqparse_copy = reqparse.copy()
reqparse_copy.remove_argument('email')
reqparse_copy.add_argument('username', type=str, required=True, help='Invalid username', location='json')
reqparse_copy.add_argument('password', type=str, required=True, help='Invalid password', location='json')


class UserRegister(Resource):

    def post(self):
        args = reqparse.parse_args()
        username = args['username']
Пример #17
0
 def get(self):
     parser.add_argument('type')
     parser.add_argument('position')
     args = parser.parse_args(req=request)
     stock_tushare.sync_daily()
     return {'result': 0, 'message': ''}
Пример #18
0
from flask_restful import Resource, reqparse, fields, marshal

from mta_tracker.models import db, Lines

response_fields = {
    'line': fields.String,
    'date': fields.String,
    'query_type': fields.String,
    'value': fields.String
}

reqparse = reqparse.RequestParser()
reqparse.add_argument('line',
                      type=str,
                      required=True,
                      help="No subway line provided.",
                      location='args')


class LineUptime(Resource):
    def __init__(self):
        self.reqparse = reqparse

    def get(self):
        """
        Return the uptime (fraction of time not delayed) for a given subway 
        line.
        
        :param line: Name of subway line
        :return: Information related to uptime
Пример #19
0
from flask import Flask
from flask_restful import Api, Resource,reqparse
import pandas as pd
import numpy as np
import sqlite3

app = Flask(__name__)
api = Api(app)

#element for post: qurey_time
#繼承
reqparse = reqparse.RequestParser()
reqparse.add_argument('query_time', type = str, required = True,
            help = 'No time provided', location = 'json')
#寫一個連接資料庫並且抓出我們要的資料的函式
#注意:因為不同表格所以需要額外指出連接的表格
def return_data(query_time,table_name):
    conn = sqlite3.connect('flask.db')
    c=conn.cursor()
    content=c.execute("SELECT *  from {0} Where 年月日 LIKE '{1}%'".format(table_name,query_time) )
    table=content.fetchall()
    indx=c.execute("PRAGMA table_info(%s)" % table_name) 
    index=indx.fetchall()
    indx=list(np.array(index)[:,1])
    data_list=[]
    for i in table:
        data_list.append(dict(zip(indx,i)))
    conn.commit()
    conn.close()
    return data_list
Пример #20
0
from flask_restful import reqparse, Resource
from werkzeug.exceptions import Forbidden

from blog.models import User

reqparse = reqparse.RequestParser()
reqparse.add_argument('email', required=True, location='json', type=str)
reqparse.add_argument('password', required=True, location='json', type=str)


class LoginView(Resource):
    def post(self):
        args = reqparse.parse_args()
        user = User.query.filter_by(email=args.email).first()

        if not user:
            raise Forbidden('Email Error')
        if not user.verify_password(args.password):
            raise Forbidden('Password Error')

        token = user.generate_confirm_token()
        return {
            'token': token,
            'username': user.username,
            'permission': user.role.permissions,
            'avatar': user.avatar
        }