from flask_restful import fields, reqparse import datetime # define Items output fields item_fields = { 'id': fields.Integer, 'name': fields.String, 'description': fields.String, 'start_date': fields.String, 'end_date': fields.String, 'user': { 'id': fields.Integer(attribute='user_id'), 'name': fields.String(attribute='user_name') }, 'place': { 'id': fields.Integer(attribute='place_id'), 'name': fields.String(attribute='place_name') }, 'item_type': { 'id': fields.Integer(attribute='itemtype_id'), 'name': fields.String(attribute='itemtype_name') } } # define Places output fields place_fields = { 'id': fields.Integer, 'name': fields.String, 'description': fields.String, }
parse_room_post=reqparse.RequestParser() parse_room_post.add_argument("name", type=str) parse_room_post.add_argument("detail", type=str) parse_room_post.add_argument("action", type=str, required=True, help="请输入请求参数") parse_room_post_join=parse_room_post.copy() parse_room_post_join.add_argument("roomid", type=int, required=True, help="请输入房间id") parse_room_patch=reqparse.RequestParser() parse_room_patch.add_argument("name", type=str) parse_room_patch.add_argument("detail", type=str) parse_room_patch.add_argument("roomid", type=int, required=True, help="请输入房间id") room_fields={ "roomid": fields.Integer(attribute='id'), "host_id":fields.Integer, "url":fields.String, "name":fields.String, "icon":fields.String, "detail":fields.String, } single_room_fields={ "status":fields.Integer, "msg":fields.String, "data":fields.Nested(room_fields), } rooms_fields = { "status": fields.Integer, "msg": fields.String, "data": fields.List(fields.Nested(room_fields)),
section = { "type": section_type(), "id": fields.String(), "mode": enum_type(attribute="street_network.mode"), "duration": Integer(), "from": section_place(place, attribute="origin"), "to": section_place(place, attribute="destination"), "links": SectionLinks(attribute="uris"), "display_informations": PbField(display_informations_vj, attribute='pt_display_informations'), "additional_informations": NonNullList(PbEnum(response_pb2.SectionAdditionalInformationType)), "geojson": SectionGeoJson(), "path": NonNullList(NonNullNested({"length": Integer(), "name": fields.String(), "duration": Integer(), "direction": fields.Integer()}), attribute="street_network.path_items"), "transfer_type": enum_type(), "stop_date_times": NonNullList(NonNullNested(stop_date_time)), "departure_date_time": DateTime(attribute="begin_date_time"), "base_departure_date_time": DateTime(attribute="base_begin_date_time"), "arrival_date_time": DateTime(attribute="end_date_time"), "base_arrival_date_time": DateTime(attribute="base_end_date_time"), "co2_emission": NonNullNested({ 'value': fields.Raw, 'unit': fields.String }), } cost = { 'value': fields.String(),
import datetime from flask_restful import Resource, fields, marshal_with, abort from wfdb.models import db, Movie, Actor from .parsers import movie_post_parser, movie_put_parser from .auth import abort_if_no_admin_auth movie_fields = { 'id': fields.Integer(), 'name': fields.String(), 'summary': fields.String(), 'release_date': fields.DateTime(dt_format='iso8601'), 'director_id': fields.Integer() } class MovieAPI(Resource): @marshal_with(movie_fields) def get(self, movie_id=None): if movie_id: return Movie.query.get_or_404(movie_id) else: return Movie.query.all() def post(self, movie_id=None): if movie_id: abort(400) else: args = movie_post_parser.parse_args(strict=True) abort_if_no_admin_auth(args['token'])
import logging, json, models, datetime from flask import request, g, abort from flask_restful import Resource, marshal_with, fields from extensions import auth, db from endpoints import api logger = logging.getLogger(__name__) item_fields = { "item_id": fields.Integer(attribute="id"), "item_name": fields.String(attribute="name"), "price": fields.Integer(), "amount": fields.Integer } class Items(Resource): @marshal_with(item_fields) def get(self): items = models.Item.query.all() for item in items: item.price = item.get_current_price() return items class Item(Resource): @marshal_with(item_fields) def get(self, item_id=None): if item_id is None: abort(404) item = models.Item.query.filter_by(id=item_id).first() item.price = item.get_current_price()
class CommentCache(object): """ 评论信息缓存 """ comment_fields = { 'com_id': fields.Integer(attribute='id'), 'aut_id': fields.Integer(attribute='user_id'), 'pubdate': fields.DateTime(attribute='ctime', dt_format='iso8601'), 'content': fields.String(attribute='content'), 'is_top': fields.Integer(attribute='is_top') } def __init__(self, comment_id): self.key = 'comm:{}'.format(comment_id) self.comment_id = comment_id def get(self): """ 获取 """ rc = current_app.redis_cluster try: comment = rc.get(self.key) except RedisError as e: current_app.logger.error(e) return None else: if comment is None: return None comment = json.loads(comment) comment = CommentCache.fill_fields(comment) return comment @classmethod def fill_fields(cls, comment): """ 补充字段 :param comment: :return: """ _user = cache_user.UserProfileCache(comment['aut_id']).get() comment['aut_name'] = _user['name'] comment['aut_photo'] = _user['photo'] comment['like_count'] = cache_statistic.CommentLikingCountStorage.get(comment['com_id']) comment['reply_count'] = cache_statistic.CommentReplyCountStorage.get(comment['com_id']) return comment @classmethod def get_list(cls, comment_ids): """ 批量获取 """ rc = current_app.redis_cluster comments = {} need_db_query = [] sorted_comments = [] # 从缓存查询,没有就记录 for comment_id in comment_ids: comment = CommentCache(comment_id).get() if comment is None: need_db_query.append(comment_id) else: comments[comment_id] = comment sorted_comments.append(comment) # 数据库查询缓存缺失的 if not need_db_query: return sorted_comments else: ret = Comment.query.filter(Comment.id.in_(need_db_query), Comment.status == Comment.STATUS.APPROVED).all() pl = rc.pipeline() for comment in ret: # 处理序列化 formatted_comment = marshal(comment, cls.comment_fields) # 保存缓存 pl.setex(CommentCache(comment.id).key, constants.CommentCacheTTL.get_val(), json.dumps(formatted_comment)) # 处理字段 formatted_comment = cls.fill_fields(formatted_comment) comments[comment.id] = formatted_comment try: pl.execute() except RedisError as e: current_app.logger.error(e) # 排序 sorted_comments = [] for comment_id in comment_ids: sorted_comments.append(comments[comment_id]) return sorted_comments def exists(self): """ 判断缓存是否存在 """ rc = current_app.redis_cluster try: ret = rc.get(self.key) except RedisError as e: current_app.logger.error(e) ret = None if ret: return False if ret == b'-1' else True else: # 数据库查询 comment = self.save() if comment is None: # 不存在, 设置缓存,防止击穿 try: rc.setex(self.key, constants.CommentNotExistsCacheTTL.get_val(), '-1') except RedisError as e: current_app.logger.error(e) return False else: return True def save(self, comment=None): """ 保存 """ if comment is None: # 数据库查询 comment = Comment.query.filter(Comment.id == self.comment_id, Comment.status == Comment.STATUS.APPROVED).all() if comment is None: return None else: # 设置缓存 formatted_comment = marshal(comment, self.comment_fields) try: current_app.redis_cluster.setex(self.key, constants.CommentCacheTTL.get_val(), json.dumps(formatted_comment)) except RedisError as e: current_app.logger.error(e) return formatted_comment def clear(self): current_app.redis_cluster.delete(self.key)
from flask_restful import Resource, fields, marshal_with, marshal from App.models import Letter, City city_fields = { "id": fields.Integer, 'regionName': fields.String, 'CityCode': fields.Integer, 'pinYin': fields.String, 'parentId': fields.Integer(default=0) } city_list_fields = { "A": fields.List(fields.Nested(city_fields)), } result_fields = { "returnCode": fields.String, "returnValue": fields.Nested(city_list_fields) } class CityResource(Resource): def get(self): returnValue = {} letters = Letter.query.all() city_list_fields_dynamic = {} for letter in letters: cities = City.query.filter(City.c_letter == letter.id).all() returnValue[letter.letter] = cities city_list_fields_dynamic[letter.letter] = fields.List(fields.Nested(city_fields))
class ArticleDetailCache(object): """ 文章详细内容缓存 """ article_fields = { 'art_id': fields.Integer(attribute='id'), 'title': fields.String(attribute='title'), 'pubdate': fields.DateTime(attribute='ctime', dt_format='iso8601'), 'content': fields.String(attribute='content.content'), 'aut_id': fields.Integer(attribute='user_id'), 'ch_id': fields.Integer(attribute='channel_id'), } def __init__(self, article_id): self.key = 'art:{}:detail'.format(article_id) self.article_id = article_id def get(self): """ 获取文章详情信息 :return: """ # 查询文章数据 rc = current_app.redis_cluster try: article_bytes = rc.get(self.key) except RedisError as e: current_app.logger.error(e) article_bytes = None if article_bytes: # 使用缓存 article_dict = json.loads(article_bytes) else: # 查询数据库 article = Article.query.options( load_only(Article.id, Article.user_id, Article.title, Article.is_advertising, Article.ctime, Article.channel_id)).filter_by( id=self.article_id, status=Article.STATUS.APPROVED).first() article_dict = marshal(article, self.article_fields) # 缓存 article_cache = json.dumps(article_dict) try: rc.setex(self.key, constants.ArticleDetailCacheTTL.get_val(), article_cache) except RedisError: pass user = cache_user.UserProfileCache(article_dict['aut_id']).get() article_dict['aut_name'] = user['name'] article_dict['aut_photo'] = user['photo'] return article_dict def clear(self): current_app.redis_cluster.delete(self.key)
model_fields = { 'model_id': fields.String, 'model_description': fields.String, 'created': fields.String, 'modified': fields.String, 'number_of_topics': fields.Integer, 'status': fields.String, 'training_documents_count': fields.Integer, 'training_parameters': { 'min_document_frequency': fields.Float(attribute='training_parameters.min_document_frequency'), 'max_document_frequency': fields.Float(attribute='training_parameters.max_document_frequency'), 'chunk_size': fields.Integer(attribute='training_parameters.chunk_size'), 'min_passes': fields.Integer(attribute='training_parameters.min_passes') }, 'topics': fields.Url('topics', absolute=True), 'documents': fields.Url('documents', absolute=True), } models_fields = {'models': fields.List(fields.Nested(model_fields))} document_fields = { 'document_id': fields.String, 'text': fields.String, 'assigned_topics': fields.List(fields.Nested(topic_assignment_fields)), 'model_id': fields.String, 'threshold': fields.Float,
class LegalizeListResource(Resource): """ 用户认证申请记录 """ legalize_fields = { 'legalize_id': fields.Integer(attribute='id'), # 申请记录id 'account': fields.String(attribute='user.account'), # 账号 'name': fields.String(attribute='user.name'), # 用户名 'create_time': fields.DateTime(attribute='ctime', dt_format='iso8601'), # 申请认证时间 'type': fields.Integer(attribute='type'), # 认证类型 'status': fields.Integer(attribute='status'), # 状态 } method_decorators = { 'get': [mis_permission_required('legalize-list-get')], 'post': [mis_permission_required('legalize-list-post')], 'put': [mis_permission_required('legalize-list-put')], } def get(self): """ 获取用户认证申请记录 """ args_parser = RequestParser() args_parser.add_argument('page', type=inputs.positive, required=False, location='args') args_parser.add_argument('per_page', type=inputs.int_range(constants.PER_PAGE_MIN, constants.PER_PAGE_MAX, 'per_page'), required=False, location='args') args_parser.add_argument('status', type=inputs.positive, location='args') args_parser.add_argument('order_by', location='args') args = args_parser.parse_args() page = constants.DEFAULT_PAGE if args.page is None else args.page per_page = constants.DEFAULT_PER_PAGE if args.per_page is None else args.per_page legalizes = LegalizeLog.query if args.status is not None: legalizes = legalizes.filter_by(status=args.status) if args.order_by is not None: if args.order_by == 'id': legalizes = legalizes.order_by(LegalizeLog.id.asc()) else: legalizes = legalizes.order_by(LegalizeLog.utime.desc()) else: legalizes = legalizes.order_by(LegalizeLog.utime.desc()) total_count = legalizes.count() legalizes = legalizes.offset(per_page * (page - 1)).limit(per_page).all() ret = marshal(legalizes, LegalizeListResource.legalize_fields, envelope='legalizes') ret['total_count'] = total_count return ret def post(self): """ *** 测试 """ user_id = 8 # qual = Qualification(user_id=user_id, # name='wangzq', # id_number='440982199006091854', # industry='软件', # company='cz', # position='python', # add_info='nothing', # id_card_front='id_card_front', # id_card_back='id_card_back', # id_card_handheld='id_card_handheld', # qualification_img='qualification_img', # ) # db.session.add(qual) # db.session.commit() legal = LegalizeLog(user_id=user_id, type=LegalizeLog.TYPE.REAL_NAME, status=LegalizeLog.STATUS.PROCESSING) db.session.add(legal) db.session.commit() return marshal(legal, LegalizeListResource.legalize_fields), 201 def put(self): """ 批量通过/驳回 """ json_parser = RequestParser() json_parser.add_argument('legalize_ids', action='append', type=inputs.positive, required=True, location='json') json_parser.add_argument('status', type=inputs.int_range(2, 3), required=True, location='json') json_parser.add_argument('reject_reason', location='json') args = json_parser.parse_args() legalizes = LegalizeLog.query.filter( LegalizeLog.id.in_(args.legalize_ids)) user_ids = [legal.user_id for legal in legalizes.all()] count = legalizes.update({'status': args.status}, synchronize_session=False) if args.status == LegalizeLog.STATUS.REJECT: legalizes.update( {'reject_reason': args.reject_reason or '资料不通过,驳回'}, synchronize_session=False) User.query.filter(User.id.in_(user_ids)).update( {'is_media': False}, synchronize_session=False) elif args.status == LegalizeLog.STATUS.APPROVED: User.query.filter(User.id.in_(user_ids)).update( {'is_media': True}, synchronize_session=False) db.session.commit() return {'count': count}, 201
class ArticleInfoCache(object): """ 文章基本信息缓存 """ article_info_fields_db = { 'title': fields.String(attribute='title'), 'aut_id': fields.Integer(attribute='user_id'), 'pubdate': fields.DateTime(attribute='ctime', dt_format='iso8601'), 'ch_id': fields.Integer(attribute='channel_id'), 'allow_comm': fields.Integer(attribute='allow_comment'), } def __init__(self, article_id): self.key = 'art:{}:info'.format(article_id) self.article_id = article_id def save(self): """ 保存文章缓存 """ rc = current_app.redis_cluster article = Article.query.options(load_only(Article.id, Article.title, Article.user_id, Article.channel_id, Article.cover, Article.ctime, Article.allow_comment))\ .filter_by(id=self.article_id, status=Article.STATUS.APPROVED).first() if article is None: return article_formatted = marshal(article, self.article_info_fields_db) article_formatted['cover'] = article.cover # 判断是否置顶 try: article_formatted['is_top'] = ChannelTopArticlesStorage( article.channel_id).exists(self.article_id) except RedisError as e: current_app.logger.error(e) article_formatted['is_top'] = 0 try: rc.setex(self.key, constants.ArticleInfoCacheTTL.get_val(), json.dumps(article_formatted)) except RedisError as e: current_app.logger.error(e) return article_formatted def _fill_fields(self, article_formatted): """ 补充字段 """ article_formatted['art_id'] = self.article_id # 获取作者名 author = cache_user.UserProfileCache(article_formatted['aut_id']).get() article_formatted['aut_name'] = author['name'] article_formatted[ 'comm_count'] = cache_statistic.ArticleCommentCountStorage.get( self.article_id) article_formatted[ 'like_count'] = cache_statistic.ArticleLikingCountStorage.get( self.article_id) article_formatted[ 'collect_count'] = cache_statistic.ArticleCollectingCountStorage.get( self.article_id) return article_formatted def get(self): """ 获取文章 :return: {} """ rc = current_app.redis_cluster # 从缓存中查询 try: article = rc.get(self.key) except RedisError as e: current_app.logger.error(e) article = None if article: article_formatted = json.loads(article) else: article_formatted = self.save() if not article_formatted: return None article_formatted = self._fill_fields(article_formatted) del article_formatted['allow_comm'] return article_formatted def exists(self): """ 判断文章是否存在 :return: bool """ rc = current_app.redis_cluster # 此处可使用的键有三种选择 user:{}:profile 或 user:{}:status 或 新建 # status主要为当前登录用户,而profile不仅仅是登录用户,覆盖范围更大,所以使用profile try: ret = rc.get(self.key) except RedisError as e: current_app.logger.error(e) ret = None if ret is not None: return False if ret == b'-1' else True else: # 缓存中未查到 article = self.save() if article is None: return False else: return True def determine_allow_comment(self): """ 判断是否允许评论 """ rc = current_app.redis_cluster try: ret = rc.get(self.key) except RedisError as e: current_app.logger.error(e) ret = None if ret is None: article_formatted = self.save() else: article_formatted = json.loads(ret) return article_formatted['allow_comm'] def clear(self): rc = current_app.redis_cluster rc.delete(self.key)
#!/usr/bin/env python # encoding: utf-8 """ @author: zhanghe @software: PyCharm @file: response.py @time: 2019-09-27 11:30 """ from __future__ import unicode_literals from flask_restful import fields fields_item = { 'id': fields.Integer(attribute='id'), 'code': fields.String(attribute='code'), 'name': fields.String(attribute='name'), 'applicant_id': fields.Integer(attribute='applicant_id'), 'grade_id': fields.Integer(attribute='grade_id'), 'style': fields.String(attribute='style'), 'sku': fields.String(attribute='sku'), 'brand': fields.String(attribute='brand'), 'period': fields.Integer(attribute='period'), 'req_date': fields.DateTime(dt_format=b'iso8601'), 'note': fields.String(attribute='note'), 'arr_date': fields.DateTime(dt_format=b'iso8601'), 'create_time': fields.DateTime(dt_format=b'iso8601'), 'update_time': fields.DateTime(dt_format=b'iso8601'), }
from flask_restful import Resource, fields, marshal_with from .fields import HTMLField from flask import abort from webapp.models import Post, User, db, Tag from .parsers import post_get_parser, post_post_parser, post_put_parser, post_delete_parser import datetime nested_tag_fields = {'id': fields.Integer(), 'title': fields.String()} post_fields = { 'author': fields.String(attribute=lambda x: x.author.username), 'title': fields.String(), 'text': HTMLField(), 'tags': fields.List(fields.Nested(nested_tag_fields)), 'publish_date': fields.DateTime(dt_format='iso8601') } class PostApi(Resource): # Resource是Methodview的子类 @marshal_with(post_fields) def get(self, post_id=None): if post_id: post = Post.query.get(post_id) if not post: abort(404) return post else: args = post_get_parser.parse_args() page = args['page'] or 1 if args['user']:
#!/usr/bin/env python # encoding: utf-8 """ @author: zhanghe @software: PyCharm @file: sale_delivery.py @time: 2019-04-26 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 = {
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 methysurvival = Blueprint("methysurvival", __name__) api = Api(methysurvival) model_methysurvivaltable = { "entrez": fields.Integer(attribute="entrez"), "symbol": fields.String(attribute="symbol"), "cancertype": fields.String(attribute="cancertype"), "log_rank_p": fields.Float(attribute="log_rank_p"), "cox_p": fields.Float(attribute="cox_p"), "HR": fields.Float(attribute="HR"), "higher_risk_of_death": fields.String(attribute="higher_risk_of_death"), } class MethySurvivalTable(Resource): @marshal_with(model_methysurvivaltable) 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 common.decorators import admin_client_login_required, permission_required from common.movieModel import MovieModel from common.utils import uploads_images_path, del_file from flask_tpp.config import ADMIN_CLIENT_PERMISSION from flask_tpp.ext import db movie_field = { 'showname': fields.String(attribute='show_name'), 'shownameen': fields.String(attribute='show_name_en'), 'director': fields.String(attribute='director'), 'leadingRole': fields.String(attribute='leading_role'), 'type': fields.String(attribute='type'), 'country': fields.String(attribute='country'), 'language': fields.String(attribute='language'), 'duration': fields.Integer(attribute='duration'), 'screeningmodel': fields.String(attribute='screening_model'), 'openday': fields.String(attribute='open_day'), 'backgroundpicture': fields.String(attribute='background_picture'), 'flag': fields.Integer(attribute='flag'), 'isdelete': fields.Boolean(attribute='is_delete'), } parser = reqparse.RequestParser() movie_add_parser = parser.copy() movie_add_parser.add_argument('show_name', location='form', type=str, required=True, help='请输入电影名称') movie_add_parser.add_argument('show_name_en',
} } """ # { # "status':200 # 'msg':'success' # data:[ # {}, # {} # ] # } # 嵌套类型 Nested banner_fields = {'bid': fields.Integer(default=1), 'path': fields.String} result = { 'status': fields.Integer, 'msg': fields.String, 'data': fields.List(fields.Nested(banner_fields)) } class BannerResource(Resource): @marshal_with(fields=result) def get(self): banners = Banner.query.all() result = {'status': 200, 'msg': 'success', 'data': banners} return result
from geventwebsocket import WebSocketError from werkzeug.utils import secure_filename from App.apis.api_constant import HTTP_OK from App.apis.model_utils import login_required, change_filename from App.models import Room, Message from App.settings import PIC_DIR, FILE_DIR parse_room_message = reqparse.RequestParser() parse_room_message.add_argument("token", type=str, required=True, help="请输入令牌") parse_room_message.add_argument("roomid", type=int, required=True, help="请输入房间id") parse_room_message.add_argument("search_type", type=int) parse_room_message.add_argument("search_info", type=str) message_fields = { "user_id": fields.Integer(attribute='message_author'), "from_user": fields.String, "roomid": fields.Integer(attribute='message_room'), "time": fields.String(attribute='timestamp'), "msg": fields.String(attribute='body'), "type": fields.Integer, "user_icon": fields.String, } single_message_fields = { "status": fields.Integer, "msg": fields.String, "data": fields.Nested(message_fields), } messages_fields = { "status": fields.Integer,
import json, uuid, logging, datetime from flask import request, g, abort from flask_restful import Resource, marshal_with, fields from endpoints import api from extensions import db, auth import models logger = logging.getLogger(__name__) user_fields = { "user_id" : fields.Integer(attribute="id"), "user_name" : fields.String, "balance" : fields.Integer, "stock_value" : fields.Integer, "total" : fields.Integer } user_register_fields = { "user_id" : fields.Integer(attribute="id"), "user_name" : fields.String, "balance" : fields.Integer, "token" : fields.String, } item_fields = { "item_id" : fields.Integer(attribute="item_id"), "item_name" : fields.String(attribute="item.name"), "amount" : fields.Integer, "price" : fields.Integer, } user_status_fields = {
from flask_restful import Resource, fields, marshal_with, marshal from App.models import Letter, City city_fields = { "id": fields.Integer, "regionName": fields.String, "cityCode": fields.Integer, "pinYin": fields.String, "parentId": fields.Integer(default=0) } city_list_fields = { "A": fields.List(fields.Nested(city_fields)), "B": fields.List(fields.Nested(city_fields)), "C": fields.List(fields.Nested(city_fields)), "D": fields.List(fields.Nested(city_fields)), "E": fields.List(fields.Nested(city_fields)), "F": fields.List(fields.Nested(city_fields)), "G": fields.List(fields.Nested(city_fields)), "H": fields.List(fields.Nested(city_fields)), "J": fields.List(fields.Nested(city_fields)), "K": fields.List(fields.Nested(city_fields)), "L": fields.List(fields.Nested(city_fields)), "M": fields.List(fields.Nested(city_fields)), "N": fields.List(fields.Nested(city_fields)), "P": fields.List(fields.Nested(city_fields)), "Q": fields.List(fields.Nested(city_fields)), "R": fields.List(fields.Nested(city_fields)), "S": fields.List(fields.Nested(city_fields)), "T": fields.List(fields.Nested(city_fields)),
'size':10 总页数 } movies:[ {}, 这个是查询出的数据详细 {}, ] } } """ pager = { # 返回的的总记录数 'total': fields.Integer, # 设定的页数 'pages': fields.Integer(default=10), } movies = { 'mid':fields.Integer, 'chinese_name': fields.String, 'director': fields.String, 'leadingRole': fields.String, 'country': fields.String, 'duration': fields.String, 'bg_pic': fields.String, } data = { # 热映分页数据 'pager1': fields.Nested(pager),
from flask_restful import fields from flask_restful.reqparse import RequestParser from cebulany.models import PaymentType from cebulany.resources.model import ModelListResource, ModelResource from cebulany.resources.types import boolean resource_fields = { 'id': fields.Integer(), 'name': fields.String(), 'color': fields.String(), 'has_members': fields.Boolean(), 'show_details_in_report': fields.Boolean(), 'show_count_in_report': fields.Boolean(), } parser = RequestParser() parser.add_argument('name', required=True) parser.add_argument('color', required=True, type=str) parser.add_argument('has_members', required=False, type=bool) parser.add_argument('show_details_in_report', required=False, type=bool) parser.add_argument('show_count_in_report', required=False, type=bool) query_parser = RequestParser() query_parser.add_argument('has_members', type=boolean) class PaymentTypeListResource(ModelListResource): cls = PaymentType parser = parser resource_fields = resource_fields
from flask_restful import fields from flask_restful import Resource,marshal_with,reqparse from flask import request from application.api.common.user import online from application.api.model.models import Collect,Note from application.api.common.response import response from application.api.common.utils import time_format,get_db,model_to_dict base_fields = { 'code': fields.Integer(default=200), 'message': fields.String(default='success') } collect_fields = fields.Nested({ 'note_id': fields.Integer(), 'title': fields.String(attribute='title'), 'content': fields.String(attribute='content'), 'status': fields.Integer(default=1), 'add_time': fields.DateTime(), 'up_time': fields.DateTime(), 'is_collect':fields.Boolean(default=True) }) resource_fields = base_fields resource_fields['data'] = fields.List(collect_fields) class CollectResource(Resource): @marshal_with(resource_fields) def get(self): collects = online.user.collect note_list = [] for collect in collects: collect.note.is_collect = True note_list.append(
from flask import g, request from flask_restful import abort, fields, marshal_with, Resource from app.auth import authorize from app.models.user import User user_resource_fields = { 'id': fields.Integer, 'email': fields.String, 'name': fields.String, 'calories_per_day': fields.Integer(default=None), 'active': fields.Boolean(attribute=lambda m: not m.deleted), 'is_admin': fields.Boolean, 'is_user_manager': fields.Boolean, } class UserResource(Resource): method_decorators = [authorize] @marshal_with(user_resource_fields, envelope='user') def get(self, user_id): user = User.query.filter(User.id == user_id).one_or_none() if user is None: abort(404) if user.id != g.user.id and not g.user.can_update_users:
class PublisherUrl(fields.Url): def __init__(self, absolute=False, scheme=None): super(PublisherUrl, self).__init__('publisher_get_single', absolute, scheme) def output(self, key, obj): if obj.publisher_gid is None: return None obj.entity_gid = obj.publisher_gid return super(PublisherUrl, self).output(key, obj) LANGUAGE_STUB = { 'language_id': fields.Integer(attribute='id'), 'name': fields.String } LANGUAGE = LANGUAGE_STUB.copy() LANGUAGE.update({ 'iso_code_2t': fields.String, 'iso_code_2b': fields.String, 'iso_code_1': fields.String, 'iso_code_3': fields.String, 'frequency': fields.Integer }) LANGUAGE_LIST = { 'offset': fields.Integer, 'count': fields.Integer,
from flask_restful import fields from .custom import Num, EdgeUrl, PaginateUrl getCommentField = { "id": fields.Integer, "time": fields.DateTime(attribute="timestamp"), "author_name": fields.String(attribute="username"), "article_id": fields.Integer(attribute="postid"), "body": fields.String, "urls": { "arthor": fields.Url("api.user", absolute=True), "post": fields.Url("api.post", absolute=True), }, } getPostCommentsField = { "prev": EdgeUrl("api.post_comments", 0), "next": EdgeUrl("api.post_comments", 1), "all_comments": fields.Integer(attribute="total"), "all_pages": fields.Integer(attribute="pages"), "urls": fields.List( PaginateUrl("api.comment", "commentid", "id"), attribute="items" ), }
class DepositionType(object): """Deposition type. A base class for the deposition types to ensure certain properties are defined on each type. A deposition type is just a BibWorkflow with a couple of extra methods. To customize rendering behavior of the workflow for a given deposition type you can override the render_error(), render_step() and render_completed() methods. """ workflow = [] """ Workflow definition """ name = "" """ Display name for this deposition type """ name_plural = "" """ Plural version of display name for this deposition type """ enabled = False """ Determines if type is enabled - TODO: REMOVE""" default = False """ Determines if type is the default - warnings are issed if conflicts exsists TODO: remove """ deletable = False """ Determine if a deposition is deletable after submission. """ editable = False """ Determine if a deposition is editable after submission. """ stopable = False """ Determine if a deposition workflow can be stopped (i.e. discard changes). """ group = None """ Name of group to include this type in. """ api = False """ Determines if API is enabled for this type (requires workflow to be compatible with the API). """ draft_definitions = {'_default': None} """ Dictionary of all drafts for this deposition type """ marshal_file_fields = dict( checksum=fields.String, filename=fields.String(attribute='name'), id=fields.String(attribute='uuid'), filesize=fields.String(attribute='size'), ) """ REST API structure of a file """ marshal_draft_fields = dict( metadata=fields.Raw(attribute='values'), completed=fields.Boolean, id=fields.String, ) """ REST API structure of a draft """ marshal_deposition_fields = dict( id=fields.Integer, title=fields.String, created=UTCISODateTime, modified=UTCISODateTime, owner=fields.Integer(attribute='user_id'), state=fields.String, submitted=fields.Boolean, files=fields.Nested(marshal_file_fields), drafts=fields.Nested(marshal_draft_fields, attribute='drafts_list'), ) """ REST API structure of a deposition """ @classmethod def default_draft_id(cls, deposition): """Default draft id.""" return '_default' @classmethod def render_error(cls, dummy_deposition): """ Render a page when deposition had an workflow error. Method can be overwritten by subclasses to provide custom user interface. """ flash('%(name)s deposition has returned error.' % {'name': cls.name}, 'error') return redirect(url_for('.index')) @classmethod def render_step(self, deposition): """ Render a page for a given deposition step. Method can be overwritten by subclasses to provide custom user interface. """ ctx = deposition.get_render_context() if ctx: return render_template(**ctx) else: return render_template( 'deposit/error.html', **dict( depostion=deposition, deposition_type=(None if deposition.type.is_default() else deposition.type.get_identifier()), uuid=deposition.id, my_depositions=Deposition.get_depositions( current_user, type=deposition.type), )) @classmethod def render_completed(cls, dummy_deposition): """Render page when deposition was successfully completed. (i.e workflow just finished successfully). Method can be overwritten by subclasses to provide custom user interface. """ flash('%(name)s was successfully finished.' % {'name': cls.name}, 'success') return redirect(url_for('.index')) @classmethod def render_final(cls, deposition): """Render page when deposition was *already* successfully completed. (i.e a finished workflow is being executed a second time). This allows you render e.g. a preview of the record. The distinction between render_completed and render_final is primarily useful for the REST API (see api_final and api_completed) Method can be overwritten by subclasses to provide custom user interface. """ return cls.render_completed(deposition) @classmethod def api_completed(cls, deposition): """Workflow just finished processing. Workflow just finished processing so return an 202 Accepted, since usually further background processing may happen. """ return deposition.marshal(), 202 @classmethod def api_final(cls, deposition): """Workflow already finished. And the user tries to re-execute the workflow, so send a 400 Bad Request back. """ return dict( message="Deposition workflow already completed", status=400, ), 400 @classmethod def api_step(cls, deposition): """Workflow was halted during processing. The workflow task that halted processing is expected to provide a response to send back to the client. The default response code is 500 Internal Server Error. A workflow task is expected to use Deposition.set_render_context() with a dictionary which is returned to the client. Set the key 'status', to change the status code, e.g.:: d.set_render_context(dict(status=400, message="Bad request")) If no response is provided by the workflow task, it is regarded as an internal server error. """ ctx = deposition.get_render_context() if ctx: return ctx.get('response', {}), ctx.get('status', 500) return cls.api_error(deposition) @classmethod def api_error(cls, deposition): """Api error.""" return dict(message='Internal Server Error', status=500), 500 @classmethod def api_action(cls, deposition, action_id): """Api action.""" if action_id == 'run': return deposition.run_workflow(headless=True) elif action_id == 'reinitialize': deposition.reinitialize_workflow() return deposition.run_workflow(headless=True) elif action_id == 'stop': deposition.stop_workflow() return deposition.run_workflow(headless=True) raise InvalidApiAction(action_id) @classmethod def api_metadata_schema(cls, draft_id): """Get the input validation schema for this draft_id. Allows you to override API defaults. """ from wtforms.fields.core import FieldList, FormField if draft_id in cls.draft_definitions: schema = dict() formclass = cls.draft_definitions[draft_id] for fname, fclass in formclass()._fields.items(): if isinstance(fclass, FieldList): schema[fname] = dict(type='list') elif isinstance(fclass, FormField): schema[fname] = dict(type='dict') else: schema[fname] = dict(type='any') return dict(type='dict', schema=schema) return None @classmethod def marshal_deposition(cls, obj): """Generate a JSON representation for REST API of a Deposition.""" return marshal(obj, cls.marshal_deposition_fields) @classmethod def marshal_draft(cls, obj): """Generate a JSON representation for REST API of a DepositionDraft.""" return marshal(obj, cls.marshal_draft_fields) @classmethod def marshal_file(cls, obj): """Generate a JSON representation for REST API of a DepositionFile.""" return marshal(obj, cls.marshal_file_fields) @classmethod def authorize(cls, deposition, action): """Authorize.""" if action == 'create': return True # Any authenticated user elif action == 'delete': if deposition.has_sip(): return deposition.type.deletable return True elif action == 'reinitialize': return deposition.type.editable elif action == 'stop': return deposition.type.stopable elif action in ['add_file', 'remove_file', 'sort_files']: # Don't allow to add/remove/sort files after first submission return not deposition.has_sip() elif action in [ 'add_draft', ]: # Allow adding drafts when inprogress (independent of SIP exists # or not). return deposition.state == 'inprogress' else: return not deposition.has_sip() @classmethod def authorize_draft(cls, deposition, draft, action): """Authorize draft.""" if action == 'update': # If deposition allows adding a draft, then allow editing the # draft. return cls.authorize(deposition, 'add_draft') return cls.authorize(deposition, 'add_draft') @classmethod def authorize_file(cls, deposition, deposition_file, action): """Authorize file.""" return cls.authorize(deposition, 'add_file') @classmethod def get_identifier(cls): """Get type identifier (identical to workflow name).""" return cls.__name__ @classmethod def is_enabled(cls): """Check if workflow is enabled.""" # Wrapping in a method to eventually allow enabling/disabling # via configuration. return cls.enabled @classmethod def is_default(cls): """Check if workflow is the default.""" # Wrapping in a method to eventually allow configuration # via configuration. return cls.default @classmethod def run_workflow(cls, deposition): """Run workflow for the given BibWorkflowObject. Usually not invoked directly, but instead indirectly through Deposition.run_workflow(). """ if deposition.workflow_object.workflow is None or ( deposition.workflow_object.version == ObjectVersion.INITIAL and deposition.workflow_object.workflow.status == WorkflowStatus.NEW): return deposition.workflow_object.start_workflow( workflow_name=cls.get_identifier(), id_user=deposition.workflow_object.id_user, module_name="webdeposit") else: return deposition.workflow_object.continue_workflow( start_point="restart_task", ) @classmethod def reinitialize_workflow(cls, deposition): """Reinitialize workflow.""" # Only reinitialize if really needed (i.e. you can only # reinitialize a fully completed workflow). wo = deposition.workflow_object if wo.version == ObjectVersion.COMPLETED and \ wo.workflow.status == WorkflowStatus.COMPLETED: wo.version = ObjectVersion.INITIAL wo.workflow.status = WorkflowStatus.NEW # Clear deposition drafts deposition.drafts = {} @classmethod def stop_workflow(cls, deposition): """Stop workflow.""" # Only stop workflow if really needed wo = deposition.workflow_object if wo.version != ObjectVersion.COMPLETED and \ wo.workflow.status != WorkflowStatus.COMPLETED: # Only workflows which has been fully completed once before # can be stopped if deposition.has_sip(): wo.version = ObjectVersion.COMPLETED wo.workflow.status = WorkflowStatus.COMPLETED # Clear all drafts deposition.drafts = {} # Set title - FIXME: find better way to set title sip = deposition.get_latest_sip(sealed=True) title = sip.metadata.get('title', 'Untitled') deposition.title = title @classmethod def all(cls): """Get a dictionary of deposition types.""" from .registry import deposit_types return deposit_types.mapping() @classmethod def get(cls, identifier): """Get.""" try: return cls.all()[identifier] except KeyError: raise InvalidDepositionType(identifier) @classmethod def keys(cls): """Get a list of deposition type names.""" return cls.all().keys() @classmethod def values(cls): """Get a list of deposition type names.""" return cls.all().values() @classmethod def get_default(cls): """Get a list of deposition type names.""" from .registry import deposit_default_type return deposit_default_type.get() def __unicode__(self): """Return a name for this class.""" return self.get_identifier() @classmethod def all_authorized(cls, user_info=None): """Get all authorized. Return a dict of deposit types that the current user is allowed to view. """ user_info = user_info or current_user all_types = cls.all() auth_types = user_info.get('precached_allowed_deposition_types', set()) return {key: all_types[key] for key in auth_types if key in all_types}
from flask import Blueprint from flask_restful import fields, Resource, Api, marshal_with answer_fields = { "id": fields.Integer(), "text": fields.String(), "rating": fields.Integer(default=0), "question_id": fields.Integer(), } question_fields = { "id": fields.Integer(), "text": fields.String(), "subject": fields.String(), "user_id": fields.Integer(), "rating": fields.Integer(default=0), "tags": fields.List(cls_or_instance=str), "answers": fields.Nested(answer_fields, allow_null=True), } bp = Blueprint("questions", __name__, url_prefix="/questions") api = Api(bp, prefix="/api/v1") class AnswerList(Resource): @marshal_with(answer_fields) def get(self): return [ question["answers"] for question in connector.db.questions.find() ]
from flask import session, request from flask_restful import Resource, marshal, fields from sqlalchemy import and_ from app.models import User, Goods, Strategy, Collect, db goods_info = { 'gid':fields.Integer(attribute='g_id'), 'gname':fields.String(attribute='g_name'), 'gcollectnum':fields.String(attribute='g_collectnum'), 'gcommentnum':fields.String(attribute='g_commentnum'), 'gimg':fields.String(attribute='g_img'), 'gprice':fields.String(attribute='g_price') } strategy_info = { 'sid':fields.Integer(attribute='s_id'), 'sname':fields.String(attribute='s_name'), 'scommentnum':fields.String(attribute='s_commentnum'), 'scollectnum':fields.String(attribute='s_collectnum'), 'simg':fields.String(attribute='s_image'), } class CollectModel(Resource): def get(self): id = session.get('id') if id: # 获取用户 user = User.query.get(id) # 获取收藏 collects = user.collect # 商品 攻略表 is_good = []
import os from flask import request, session from flask_restful import Resource, fields, marshal from app.models import Comment, User, Recomment comment_info = { 'content': fields.String(attribute='c_content'), 'id': fields.Integer(attribute='com_id'), } recomment_info = { 'content': fields.String(attribute='nt_content'), 'name': fields.String(attribute='nt_bname'), 'id': fields.Integer(attribute='nt_id') } user_info = {'name': fields.String(attribute='u_name')} class Cqre(Resource): def get(self): comments = Comment.query.all() print(comments) cuid = [comment.co_user for comment in comments] print(cuid) commetuser = User.query.filter(User.u_id.in_(cuid)).all() #自评论表 return_recomments_dic = {} recomments_dic = {} #自评论表外键uerid