class ProjectAPI(BaseAPI): model = Project output_fields = { "id": fields.Integer, "name": fields.String, "description": fields.String, "photoUrl": fields.String(attribute="photo_url"), "websiteUrl": fields.String(attribute="website_url"), "year": fields.Integer, "ggeReduced": fields.Float(attribute="gge_reduced"), "ghgReduced": fields.Float(attribute="ghg_reduced"), }
class ProjectAPI(BaseAPI): model = Project output_fields = { 'id': fields.Integer, 'name': fields.String, 'description': fields.String, 'photoUrl': fields.String(attribute='photo_url'), 'websiteUrl': fields.String(attribute='website_url'), 'year': fields.Integer, 'ggeReduced': fields.Float(attribute='gge_reduced'), 'ghgReduced': fields.Float(attribute='ghg_reduced') }
def test_float(): values = [ ("-3.13", -3.13), (str(-3.13), -3.13), (3, 3.0), ] for value, expected in values: yield check_field, expected, fields.Float(), value
def __parse_data(self, record): dict = { **record.attrib, **record[0].attrib } cso_format = { 'author_name' : fields.String(attribute=lambda x: " ".join([x['first'], x['last']])), 'id' : fields.String(attribute = 'nid'), 'timestamp' : fields.Integer(attribute = lambda x: int(x['timestamp'])), 'lat' : fields.Float(attribute = lambda x: float(x['lat'])), 'long' : fields.Float(attribute = lambda x: float(x['longitude'])), 'snow_depth' : fields.Float(attribute = lambda x: float(x['heightOfSnowpack'])), 'source' : fields.String(default='SnowPilot') } return marshal(dict, cso_format)
class InterruptDetailsAPI(Resource): """ Flask-Restful endpoint for getting interrupt details. """ def get(self): parser = reqparse.RequestParser(bundle_errors=True) parser.add_argument('begin_time', type=self._get_datetime, required=True, help='bad begin_time, use %Y-%m-%dT%H:%M:%S') parser.add_argument('end_time', type=self._get_datetime, required=True, help='bad end_time, use %Y-%m-%dT%H:%M:%S') args = parser.parse_args() irq_details = IRQDetails(args.begin_time, args.end_time) balance_info = irq_details.get_balance_info() return marshal(balance_info, self.balanceinfo_fields, envelope='irq_details') def _get_datetime(self, value): return datetime.strptime(value,'%Y-%m-%dT%H:%M:%S') #output marshaling irqstat_fields = { 'irq_num': fields.String, 'irq_device': fields.String, 'irq_type': fields.String, 'cpu_interrupts': fields.List(fields.Integer), 'cpu_interrupt_total': fields.Integer } cpu_fields = { 'cpu': fields.String(attribute='cpu'), 'interrupts': fields.Integer(attribute='count'), 'percent': fields.Float(attribute='percent') } balanceinfo_fields = { 'cpus': fields.List(fields.Nested(cpu_fields), attribute='cpus'), 'irq_cpu_percent_distribution': fields.List(fields.Float,attribute='distribution'), 'irq_cpu_count_distribution': fields.List(fields.Integer,attribute='counts'), 'irq_distribution_metric': fields.Float(attribute='stdev'), 'irq_stats': fields.List(fields.Nested(irqstat_fields),attribute='stats') }
def generate_availability_field(): days = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ] output = {} for day in days: output[day] = fields.List(fields.List(fields.Float()), default=[]) return output
def get_field_type(attr_type): if attr_type == int: return fields.Integer() elif attr_type == str: return fields.String() elif attr_type == bool: return fields.Boolean() elif attr_type == float: return fields.Float()
class User(object): """docstring for User""" resource_fields = { 'user_id': fields.Integer(), 'email': fields.String(), 'contact': fields.String(), 'firstname': fields.String(), 'lastname': fields.String(), 'photo_url': fields.String(), 'register_date': fields.Integer(), 'longitude': fields.Float(), 'latitude': fields.Float(), 'gender': fields.String(), 'blood_type': fields.String(), 'level': fields.String(), 'status': fields.Integer() } required = ['email', 'password']
class CinemasFields: cinemas_fields = { 'cid': fields.Integer(), 'name': fields.String(), 'address': fields.String(), 'phone': fields.String(), 'score': fields.Float(), } result_fields = { 'status': fields.Integer(default=200), 'msg': fields.String(default='success'), 'data': fields.List(fields.Nested(cinemas_fields)) }
def __parse_data(self, record): cso_format = { 'author_name': fields.String(attribute='actor.full_name') or fields.String(attribute='actor.fullName'), 'id': fields.String(attribute=lambda x: x['observation']['_id']), 'timestamp': fields.Integer( attribute=lambda x: x['observation']['reported_at']), 'lat': fields.Float(attribute=lambda x: x['observation']['location'][1]), 'long': fields.Float(attribute=lambda x: x['observation']['location'][0]), 'snow_depth': fields.Float(attribute=lambda x: x['observation']['details'][0][ 'snowpack_depth']), 'source': fields.String(default='MountainHub') } return marshal(record, cso_format)
def get(self): nested_price_fields = { 'id': fields.Integer(), 'price': fields.Float(), } product_fields = { 'id': fields.Integer(), 'skus': fields.Nested(sku_fields), 'name': fields.String(), 'description': fields.String(), 'category_id': fields.Integer(), # 'prices': fields.List(fields.Nested(nested_price_fields)), } return product_fields
from flask import Blueprint, request, send_file from gsca.db import mongo from flask_restful import Api, Resource, fields, marshal_with, reqparse from gsca.utils.checkplot import CheckPlot from gsca.utils.check_survivalPlot import CheckSurvivalPlot gdsc = Blueprint("gdsc", __name__) api = Api(gdsc) model_gdsctable = { "entrez": fields.Integer(attribute="entrez"), "symbol": fields.String(attribute="symbol"), "fdr": fields.Float(attribute="fdr"), "drug": fields.String(attribute="drug"), "cor": fields.Float(attribute="cor"), } class GDSCTable(Resource): @marshal_with(model_gdsctable) def post(self): args = request.get_json() condition = {"symbol": {"$in": args["validSymbol"]}} output = {"_id": 0} res = list() for collname in args["validColl"]: mcur = mongo.db[collname].find(condition, output) for m in mcur: m["cancertype"] = collname.rstrip("_gdsc_cor_expr") res.append(m) return res
from flask_restful import Resource, marshal_with, fields, marshal from flask_restful.reqparse import RequestParser from flask import request from apiapp.models import TSecondSource, TSource rp1 = RequestParser() view_output1 = { "source_id": fields.Integer(attribute="source_id"), "title": fields.String(attribute="title"), "hu_type": fields.String(attribute="hu_type"), "img_url": fields.String(attribute="img_url"), "sum_price": fields.Float(attribute="sum_price"), "details": fields.String(attribute="details"), "area": fields.String(attribute="area"), } view_output = { "code": fields.String, "msg": fields.String, "data": fields.List(fields.Nested(view_output1)) # ties为一个列表 } class ErhouseResource(Resource): def get(self): print("请求数据成功***********") a = request.args.get("pageCode") b = request.args.get("limitNum") a = int(a) b = int(b) ties = TSource.query.all()[a:b]
from flask import Blueprint, request, send_file from gsca.db import mongo from flask_restful import Api, Resource, fields, marshal_with, reqparse from gsca.utils.checkplot import CheckParallelPlot, CheckPlot, CheckMultiplePlot from gsca.utils.checktable import CheckTable deg = Blueprint("deg", __name__) api = Api(deg) model_degtable = { "entrez": fields.Integer(attribute="entrez"), "symbol": fields.String(attribute="symbol"), "normal": fields.Float(attribute="normal"), "tumor": fields.Float(attribute="tumor"), "fc": fields.Float(attribute="fc"), "fdr": fields.Float(attribute="fdr"), "n_normal": fields.Float(attribute="n_normal"), "n_tumor": fields.Float(attribute="n_tumor"), "cancertype": fields.String(attribute="cancertype"), } class DEGTable(Resource): @marshal_with(model_degtable) def post(self): args = request.get_json() condition = {"symbol": {"$in": args["validSymbol"]}} output = {"_id": 0} res = list() for collname in args["validColl"]: mcur = mongo.db[collname].find(condition, output)
'mobile': fields.String, 'username': fields.String, 'type': fields.Integer, 'gender': fields.Integer, 'brief': fields.String, 'bonus': fields.Float, 'orderNum': fields.Integer } client_orderComment_fields = { 'orderId': fields.Integer(attribute='order_id'), 'clientComment': fields.String(attribute='client_comment'), 'clientCommentTs': fields.String(attribute='client_comment_ts'), 'courierUserId': fields.Integer(attribute='courier_user_id'), 'courierUserName': fields.String(attribute='courier_user_name'), 'clientScore': fields.Float(attribute='client_score') } courier_orderComment_fields = { 'orderId': fields.Integer(attribute='order_id'), 'courierComment': fields.String(attribute='courier_comment'), 'courierCommentTs': fields.String(attribute='courier_comment_ts'), 'clientUserId': fields.Integer(attribute='client_user_id'), 'clientUserName': fields.String(attribute='client_user_name'), 'courierScore': fields.Float(attribute='courier_score') } orderNum_rank_fields = { 'username': fields.String, 'gender': fields.Integer, 'orderNum': fields.Integer
def __init__(self): self.name = 'clarence' self.age = 18 self.height = 1.75 self.scores = [80, 90] self.info = { 'gender': True, 'level': 8 } # 序列化规则 fields = { 'username': fields.String(attribute='name'), 'age': fields.Integer(default=20), 'height': fields.Float(), # 列表类型属性,要求列表中元素类型唯一 'scores': fields.List(fields.Integer), 'info': fields.Nested({'gender': fields.Boolean, 'level': fields.Integer}) } class DemoResource(Resource): method_decorators = {'get': [marshal_with(fields)]} def get(self): user = User() return user
@time: 2018-07-24 16:59 """ from __future__ import unicode_literals from flask_restful import fields fields_item_sale_invoice = { 'id': fields.Integer(attribute='id'), 'code': fields.String(attribute='code'), 'customer_id': fields.Integer(attribute='idcustomer'), # 客户id 'settle_id': fields.Integer(attribute='idsettlecustomer'), # 结算客户id 'address': fields.String(attribute='address'), 'linkman': fields.String(attribute='linkMan'), 'amount': fields.Float(attribute='amount'), 'amount_tax': fields.Float(attribute='taxAmount'), 'customer_address_phone': fields.String(attribute='customerAddressPhone'), 'contact_phone': fields.String(attribute='contactPhone'), 'Source_voucher_code': fields.String(attribute='SourceVoucherCode'), 'maker_id': fields.Integer(attribute='makerid'), 'maker': fields.String(attribute='maker'), 'create_time': fields.DateTime(dt_format=b'iso8601', attribute='createdtime'), 'update_time': fields.DateTime(dt_format=b'iso8601', attribute='updated'), } fields_item_sale_invoice_cn = { '主键': fields.Integer(attribute='id'), '编号': fields.String(attribute='code'), '客户': fields.Integer(attribute='idcustomer'), # 客户id '结算单位': fields.Integer(attribute='idsettlecustomer'), # 结算客户id
def test_float_decode_error(self): field = fields.Float() self.assertRaises(MarshallingException, lambda: field.output("hey", {'hey': 'Explode!'}))
def test_decimal_trash(self): self.assertRaises(MarshallingException, lambda: fields.Float().output('a', {'a': 'Foo'}))
class PrinterStatusApi(Resource): """ Api class for printer commands and printer status """ @login_required @marshal_with({ 'state': fields.Nested({ 'temperature': fields.Nested({ 'bed': fields.Nested({ 'actual': fields.Integer, 'target': fields.Integer }), 'tool': fields.Nested( { 'actual': fields.Integer, 'target': fields.Integer }, attribute="tool0") }), 'state': fields.String(attribute="state.text"), 'job': fields.Nested({ 'printTimeLeft': fields.Integer(attribute='progress.printTimeLeft'), 'completion': fields.Float(attribute='progress.completion'), 'fileName': fields.String(attribute='file.name') }) }), 'id': fields.Integer, 'name': fields.String, 'group': fields.List(fields.Nested({'name': fields.String})) }) def get(self): """Gets actual accessible printers state, including groups, name and job info""" printers = g.user.get_accessible_printers() states = [x.set_state(Printer.states.get(x.id)) for x in printers] return states, 200 @login_required def post(self): """ Issues command to printers. Possible action are settings temperature of bed and extruder, pausing and cancelling print """ args = printerControlParser.parse_args() printers = g.user.get_accessible_printers_id(args["printerId"]) for printer in printers: try: if args["bed"] is not None: print( OctoprintService.set_bed_temperature( printer, args["bed"])) if args["tool"] is not None: OctoprintService.set_tool_temperature( printer, args["tool"]) if args["pause"] is not None: OctoprintService.pause(printer) if args["cancel"] is not None: OctoprintService.cancel(printer) except (requests.ConnectionError, RuntimeError): pass return "", 200
def test_float(self): field = fields.Float() self.assertEquals('3.0', field.output("hey", {'hey': 3.0}))
from flask_restful import Api, Resource, fields, marshal_with, reqparse from pathlib import Path import subprocess import uuid from gsca.utils.checkplot import CheckPlot, CheckUUIDPlot, CheckGSVASurvivalSingleCancerType from gsca.utils.check_survivalPlot import CheckSurvivalPlot immunecnv = Blueprint("immunecnv", __name__) api = Api(immunecnv) model_immcnvcortable = { "entrez": fields.Integer(attribute="entrez"), "symbol": fields.String(attribute="symbol"), "cancertype": fields.String(attribute="cancertype"), "cell_type": fields.String(attribute="cell_type"), "cor": fields.Float(attribute="cor"), "fdr": fields.Float(attribute="fdr"), "p_value": fields.Float(attribute="p_value"), } class ImmCnvCorTable(Resource): @marshal_with(model_immcnvcortable) def post(self): args = request.get_json() condition = {"symbol": {"$in": args["validSymbol"]}} output = {"_id": 0} res = list() for collname in args["validColl"]: mcur = mongo.db[collname].find(condition, output) for m in mcur:
from flask import Blueprint, request, send_file from gsca.db import mongo from flask_restful import Api, Resource, fields, marshal_with, reqparse from gsca.utils.checkplot import CheckPlot subtype = Blueprint("subtype", __name__) api = Api(subtype) model_subtypetable = { "entrez": fields.Integer(attribute="entrez"), "symbol": fields.String(attribute="symbol"), "pval": fields.Float(attribute="pval"), "fdr": fields.Float(attribute="fdr"), "cancertype": fields.String(attribute="cancertype"), } class SubtypeTable(Resource): @marshal_with(model_subtypetable) def post(self): args = request.get_json() condition = {"symbol": {"$in": args["validSymbol"]}} output = {"_id": 0} res = list() for collname in args["validColl"]: mcur = mongo.db[collname].find(condition, output) for m in mcur: m["cancertype"] = collname.rstrip("_expr_subtype") res.append(m) return res
@software: PyCharm @file: partner.py @time: 2018-07-24 00:30 """ from __future__ import unicode_literals from flask_restful import fields fields_item_partner = { 'id': fields.Integer(attribute='id'), 'code': fields.String(attribute='code'), 'name': fields.String(attribute='name'), 'type_partner': fields.Integer(attribute='partnerType'), 'id_settle': fields.Integer(attribute='idsettlementPartner'), # 结算客户id 'advr_balance': fields.Float(attribute='AdvRBalance'), # 预收余额 'advp_balance': fields.Float(attribute='AdvPBalance'), # 预付余额 'ar_balance': fields.Float(attribute='aRBalance'), # 应收余额 'ap_balance': fields.Float(attribute='aPBalance'), # 应付余额 'disabled': fields.Integer(attribute='disabled'), 'id_sales': fields.Integer(attribute='idsaleman'), 'address': fields.String(attribute='ShipmentAddress'), 'contact': fields.String(attribute='Contact'), 'mobile': fields.String(attribute='MobilePhone'), 'tel': fields.String(attribute='TelephoneNo'), 'fax': fields.String(attribute='Fax'), 'create_time': fields.DateTime(dt_format=b'iso8601', attribute='createdTime'), 'update_time': fields.DateTime(dt_format=b'iso8601', attribute='updated'), }
) post_parser.add_argument( 'created_at', dest='createdAt', location='json', help='Creation', ) post_parser.add_argument( 'upadated_at', dest='updatedAt', location='json', help='Last update', ) arrange_fields = { "endAt": fields.Float(attribute='end_at'), "id": fields.String(attribute='_id.$oid'), "room": fields.String, "startAt": fields.Float(attribute='start_at'), "title": fields.String, "createdAt": fields.Float(attribute='created_at'), "updatedAt": fields.Float(attribute='updated_at') } created_arrangement_response = {'_id': fields.String} def getTimestamp(dt): return round(time.mktime(dt.timetuple()) + dt.microsecond / 1e6)
fields.Integer, "windcode": fields.String, "manager": fields.String(attribute="fund_fundmanager"), "predmanager": fields.String(attribute="fund_predfundmanager"), "company": fields.String(attribute="fund_corp_fundmanagementcompany"), "update_date": fields.String, "manager_info": fields.List( fields.Nested({ "netasset": fields.Float(attribute="fund_manager_totalnetasset"), "resume": fields.String(attribute="fund_manager_resume"), "gender": fields.String(attribute="fund_manager_gender"), "return": fields.Float(attribute="nav_periodicannualizedreturn"), "rank": fields.Integer })), "classify": fields.String, "setup": fields.String, "bench": fields.String,
'amount': fields.Float, 'discount_amount': fields.Float, 'unit_value': fields.Float, 'is_stock_product': fields.Boolean, 'is_discount_product': fields.Boolean, 'not_available': fields.Boolean, 'not_show_in_catalog': fields.Boolean, 'stock_text': fields.String, 'brand_id': fields.Integer, 'partner_id': fields.Integer, 'currency_id': fields.Integer, 'unit_id': fields.Integer, 'default_image_id': fields.Integer, 'default_image_data': fields.Nested(default_image_data_products), 'comments_count': fields.Integer, 'rate': fields.Float(attribute=lambda x: round(x.rate or 0, 2)), 'product_unit_data': fields.Nested(unit_data_fields), 'product_currency_data': fields.Nested(currency_data_fields), 'product_alt_unit_data': fields.Nested(unit_data_fields), 'alt_amount': fields.Float, 'alt_unit_value': fields.Float, 'alt_unit_id': fields.Integer, 'alt_discount_amount': fields.Float } brand_elements_data_fields = { 'id': fields.Integer, 'name': fields.String, 'images': fields.List(fields.Integer), 'description': fields.String, 'short_description': fields.String,
from flask import Blueprint, request, send_file from gsca.db import mongo from flask_restful import Api, Resource, fields, marshal_with, reqparse from pathlib import Path import subprocess import uuid from gsca.utils.checkplot import CheckPlot, CheckParallelPlot methycor = Blueprint("methycor", __name__) api = Api(methycor) model_methycortable = { "entrez": fields.Integer(attribute="entrez"), "symbol": fields.String(attribute="symbol"), "cancertype": fields.String(attribute="cancertype"), "spm": fields.Float(attribute="spm"), "fdr": fields.Float(attribute="fdr"), } class MethyCorTable(Resource): @marshal_with(model_methycortable) def post(self): args = request.get_json() condition = {"symbol": {"$in": args["validSymbol"]}} output = {"_id": 0} res = list() for collname in args["validColl"]: mcur = mongo.db[collname].find(condition, output) for m in mcur: m["cancertype"] = collname.rstrip("_methy_cor_expr") res.append(m)
import parser from flask import request, jsonify from flask_restful import Resource, abort, fields, marshal, marshal_with, reqparse from App.modeles import Goods goods_fields = { "id": fields.Integer, "name": fields.String(attribute="goods_name"), "goods_price": fields.Float() } goods_single_fields = { "msg": fields.String(), "status": fields.Integer, "data": fields.Nested(goods_fields), "haha": fields.String } goods_multi_fields = { "msg": fields.String, "status": fields.Integer, "data": fields.List(fields.Nested(goods_fields)), "desc": fields.String(default="lalallalal") } parser = reqparse.RequestParser() parser.add_argument("goods_name", type=str, required=True, help="please input g_name") parser.add_argument("goods_price", type=float)
@file: sale_delivery.py @time: 2018-07-24 16:58 """ from __future__ import unicode_literals from flask_restful import fields fields_item_sale_delivery = { 'id': fields.Integer(attribute='ID'), 'code': fields.String(attribute='code'), 'id_customer': fields.Integer(attribute='idcustomer'), # 客户id 'id_settle': fields.Integer(attribute='idsettlecustomer'), # 结算客户id 'is_sale_out': fields.Integer(attribute='isSaleOut'), 'recive_type': fields.Integer(attribute='reciveType'), 'amount': fields.Float(attribute='amount'), 'amount_tax': fields.Float(attribute='taxAmount'), 'receive_balance': fields.Float(attribute='ReceiveBalance'), 'makerid': fields.Integer(attribute='makerid'), 'maker': fields.String(attribute='maker'), 'create_time': fields.DateTime(dt_format=b'iso8601', attribute='createdtime'), 'update_time': fields.DateTime(dt_format=b'iso8601', attribute='updated'), } fields_item_sale_delivery_cn = { '主键': fields.Integer(attribute='ID'), '编号': fields.String(attribute='code'), '客户': fields.Integer(attribute='idcustomer'), # 客户id '结算单位': fields.Integer(attribute='idsettlecustomer'), # 结算客户id '出库状态': fields.Integer(attribute='isSaleOut'),