fields_item_sale_order = { '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'), 'contact_phone': fields.String(attribute='contactPhone'), 'delivery_mode': fields.Integer(attribute='deliveryMode'), 'receive_type': fields.Integer(attribute='reciveType'), '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_order_cn = { '主键': fields.Integer(attribute='ID'), '编号': fields.String(attribute='code'), '客户': fields.Integer(attribute='idcustomer'), # 客户id '结算单位': fields.Integer(attribute='idsettlecustomer'), # 结算客户id '地址': fields.String(attribute='address'), '联系人': fields.String(attribute='linkMan'), '金额': fields.Float(attribute='amount'), '含税金额': fields.Float(attribute='taxAmount'), '联系电话': fields.String(attribute='contactPhone'), '运输方式': fields.Integer(attribute='deliveryMode'), '收款方式': fields.Integer(attribute='reciveType'),
from flask_security import auth_token_required from flask_security.core import current_user, AnonymousUser from sqlalchemy.sql import select from sqlalchemy import func, and_, or_ from ..model import ScientificPaper, ArticlePaper, ROLE_FULL_TEXT_ACCESS from ..services.news import link_news_candidate article_fields = { "id": fields.Integer(), "title": fields.String(), "url": fields.String(), "hostname": fields.String(), "content": fields.String(attribute='text'), "publish_date": fields.DateTime(), "hidden": fields.Boolean(), "spam": fields.Boolean() } news_envelope = { "total_count": fields.Integer(), "articles": fields.Nested(article_fields) } class NewsArticleListResource(Resource): """List news articles stored in tool""" @marshal_with(news_envelope) def get(self):
db.Column('user_id', db.Integer, db.ForeignKey('user.id')) ) class MessageFormat(fields.Raw): def format(self, value): return json.loads(value) message_marshal = { 'channel': fields.String(attribute="channel.name"), 'user': fields.String(attribute="user.username"), 'type': fields.String(attribute="type"), 'data': MessageFormat(attribute="data"), 'id' : fields.String(attribute="uuid"), 'prev': fields.String(attribute="prev_uuid"), 'next': fields.String(attribute="next_uuid"), 'server_time': fields.DateTime(dt_format='iso8601', attribute="server_time") } messages_marshal = { 'messages': fields.List(fields.Nested(message_marshal)) } class Message(db.Model): __tablename__ = 'pubsub_message' id = db.Column(db.Integer, primary_key=True) uuid = db.Column(db.String(40), index=True) channel_id = db.Column(db.Integer, db.ForeignKey('pubsub_channel.id'), index=True) channel = db.relationship('Channel', backref=db.backref('messages', lazy='dynamic')) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), index=True) user = db.relationship('User', backref=db.backref('messages', lazy='dynamic')) type = db.Column(db.String(64)) data = db.Column(db.String(4096))
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)
'user_title': fields.String, } user_comment_fields = { 'id': fields.Integer, 'event_id': fields.Integer, 'user_id': fields.Integer, 'comment_by_user_firstname': fields.String(attribute='comment_by_user.firstname'), 'comment_by_user_lastname': fields.String(attribute='comment_by_user.lastname'), 'timestamp': fields.DateTime('iso8601'), 'comment': fields.String } def user_info(user, roles): return { 'id': user.id, 'token': generate_token(user), 'firstname': user.firstname, 'lastname': user.lastname,
#!/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'), 'cid': fields.Integer(attribute='cid'), 'name': fields.String(attribute='name'), 'mobile': fields.String(attribute='mobile'), 'email': fields.String(attribute='email'), 'note': fields.String(attribute='note'), 'create_time': fields.DateTime(dt_format=b'iso8601'), 'update_time': fields.DateTime(dt_format=b'iso8601'), }
cursor.execute(query, (_nome, _cpf)) conn.commit() return "Ok", 200 except Exception as e: return {'error': str(e)} projeto_pesquisa_fields = { 'id': fields.Integer, 'titulo': fields.String, 'tempo_previsto': fields.Integer, 'data_inicio': fields.DateTime(dt_format='iso8601'), 'data_conclusao': fields.DateTime(dt_format='iso8601'), 'status': fields.String } class ProjetoPesquisa(Resource): @marshal_with(projeto_pesquisa_fields, envelope=None) def get(self, id, **kwargs): try: # query = "SELECT * FROM universitat.projeto_pesquisa where id = %s" query = "SELECT p.*, s.status FROM universitat.projeto_pesquisa p, universitat.status_pesquisa s " \ "where p.status_pesquisa_id = s.id and p.id = %s" cursor.execute(query, (id))
def test_iso8601_date_field_without_offset(self): obj = {"bar": datetime(2011, 8, 22, 20, 58, 45)} field = fields.DateTime(dt_format='iso8601') self.assertEquals("2011-08-22T20:58:45", field.output("bar", obj))
def test_unsupported_datetime_format(self): obj = {"bar": datetime(2011, 8, 22, 20, 58, 45)} field = fields.DateTime(dt_format='') self.assertRaises(MarshallingException, lambda: field.output('bar', obj))
from flask_restful import fields user_inputs = { "id": fields.Integer, "username": fields.String, "email": fields.String, "fname": fields.String, "sname": fields.String, "lname": fields.String, "category": fields.Integer } subject_inputs = { "id": fields.Integer, "name": fields.String, "description": fields.String, "date_created": fields.DateTime(dt_format='rfc822'), "date_modified": fields.DateTime(dt_format='rfc822'), "created_by": fields.String, }
def test_rfc822_date_field_without_offset(self): obj = {"bar": datetime(2011, 8, 22, 20, 58, 45)} field = fields.DateTime() self.assertEquals("Mon, 22 Aug 2011 20:58:45 -0000", field.output("bar", obj))
"requestTitle": String (asset-request.title) "vehicleID": String (asset-request_vehicle.id) "vehicleType": String (vehicle.type) "vehicleFrom": DateTimeString iso8601 (asset-request_vehicle.from) "vehicleTo": DateTimeString iso8601 (asset-request_vehicle.to) "volunteerRoles": [String] (asset-request_volunteer.roles) "volunteerStatus": String (asset-request_volunteer.status) }] } ''' result_list_field = { 'requestTitle': fields.String, 'vehicleID': fields.String, 'vehicleType': fields.String, 'vehicleFrom': fields.DateTime(dt_format='iso8601'), 'vehicleTo': fields.DateTime(dt_format='iso8601'), 'volunteerRoles': fields.List(fields.String), 'volunteerStatus': fields.String, } resource_fields = { 'results': fields.List(fields.Nested(result_list_field)), } # Handle the volunteer/shifts endpoint class VolunteerShifts(Resource): @marshal_with(resource_fields) def get(self):
import os from datetime import datetime from logging import getLogger from time import sleep from flask import request from flask_restful import Resource, reqparse, fields, marshal_with, marshal from kafka.errors import NoBrokersAvailable from mongoengine import Q import dateutil.parser from database.data import Notification import json notification_fields = { 'id': fields.String(), 'user_id': fields.String(), 'timestamp': fields.DateTime(dt_format='iso8601'), 'creation_timestamp': fields.DateTime(dt_format='iso8601'), 'modified_timestamp': fields.DateTime(dt_format='iso8601'), 'type': fields.String(), 'data': fields.Raw(), 'is_active': fields.Boolean(), 'notes': fields.String() } parser = reqparse.RequestParser() parser.add_argument('id', type=str) parser.add_argument('user_id', type=str) parser.add_argument('timestamp', type=lambda x: dateutil.parser.parse(x)) parser.add_argument('creation_timestamp', type=lambda x: dateutil.parser.parse(x)) parser.add_argument('modified_timestamp',
from Apps.apis.common.user.user_utils import login_required, g from Apps.models import HistoryData from Apps.apis.common.historydata.historydata_utils import timestamp_to_str from config import DB_URI from sqlalchemy import create_engine eng = create_engine(DB_URI) historydata_fields = { "id": fields.Integer, "devName": fields.String, "alarm": fields.Integer, "dataPointName": fields.String, "type": fields.Integer, "date": fields.DateTime(dt_format='iso8601'), "groupName":fields.String, "value": fields.String } fie = {'regionName': fields.String, 'groupList': fields.List(fields.String)} regionGroupList_fields = {'code': fields.Integer, 'data': fields.List(fields.Nested(fie))} devLi_fields = {"devList":fields.List(fields.String)} devList_fields = {'code': fields.Integer, 'data': fields.Nested(devLi_fields)} dpList_fields = {'dataPointList':fields.List(fields.String)} dataPointList_fields = {'code': fields.Integer, 'data': fields.Nested(dpList_fields)} historyDataList = {"historyDataList":fields.List(fields.Nested(historydata_fields)),'total':fields.Integer}
'borrado': fields.Boolean, 'privacidad': fields.Integer, 'color': fields.String, 'comienza': fields.String, 'finaliza': fields.String, 'titulo': fields.String, 'descripcion': fields.String, 'url_imagen': fields.String, 'direccion': fields.String, 'latitud': fields.Float, 'longitud': fields.Float, 'lugar': fields.String, 'timediff_h': fields.String, 'timediff_inmins': fields.String, 'timediff_m': fields.String, 'creado_en': fields.DateTime(dt_format='iso8601'), 'actualizado_en': fields.DateTime(dt_format='iso8601') } class EventoAPI(Resource): def get(self, evento_id): evento = Evento.query.filter_by(id_evento=evento_id).first() if evento is not None: content = {'event': marshal(evento, events_fields)} return formatOutput(3000, content) else: return formatOutput(3001) api.add_resource(EventoAPI, '/events/<int:evento_id>')
def test_date_field_invalid(self): obj = {"bar": 3} field = fields.DateTime() self.assertRaises(MarshallingException, lambda: field.output("bar", obj))
from flask_restful import Resource, reqparse, fields, marshal from bank_api import models transaction_fields = { 'amount': fields.Float, 'account_id': fields.Integer, 'time': fields.DateTime(dt_format='iso8601'), 'uri': fields.Url('api.transaction') } class TransactionListAPI(Resource): def __init__(self): self.reqparse = reqparse.RequestParser() self.reqparse.add_argument('account_id', type=int, required=True, location="json") self.reqparse.add_argument('amount', type=float, required=True, location="json") super(TransactionListAPI, self).__init__() def get(self): transactions = models.Transaction.query.all() return { 'transactions': [ marshal(transaction, transaction_fields) for transaction in transactions ]
from flask_restful import Resource, fields, reqparse, marshal_with, abort from db import session from models import Person import webargs from webargs.flaskparser import use_kwargs from string import ascii_lowercase #datetime works across the stack better so we will ignore the time component #note that RFC3339 is a profile of ISO8601 #outgoing person_fields = { 'id': fields.Integer, 'lastname': fields.String, 'firstname': fields.String, 'dateofbirth': fields.DateTime(dt_format='iso8601'), #'rfc822') #will not have the Z at the end for UTC, but javascript will still accept this in a new Date() 'zipcode': fields.String } #incoming person_parser = reqparse.RequestParser() person_parser.add_argument('lastname', type=str) person_parser.add_argument('firstname', type=str) person_parser.add_argument( 'dateofbirth', type=lambda x: datetime.strptime(x, '%Y-%m-%dT%H:%M:%S.%fZ')) person_parser.add_argument('zipcode', type=str) #expecting RFC3339 date format, e.g. javascript: new Date("2015-03-25").toISOString()-->'2015-03-25T00:00:00.000Z'
} ''' # 自定义fields类型 class AuthorName(fields.Raw): def format(self, value): return value.username # 每条新闻的格式 news_fields = { 'id': fields.Integer, 'title': fields.String, 'desc': fields.String, 'datetime': fields.DateTime(attribute='date_time'), 'author': AuthorName(attribute='author'), 'url': fields.Url('news.newsdetail', absolute=True) } # 新闻api class NewsListApi(Resource): # 获取某个新闻分类下的新闻 def get(self): args = news_parser.parse_args() typeid = args.get('typeid') # newstype = NewsType.query.get(typeid) page = args.get('page', 1) pagination = News.query.filter(News.news_type_id == typeid).paginate( page=page, per_page=8)
'id':fields.Integer(), 'title':fields.String() } photo_fields={ 'id':fields.Integer(), 'url':fields.String() } post_fields={ 'id':fields.Integer(), 'title':fields.String(), 'text':fields.String(), 'type':fields.String(), 'cover':fields.String(), 'publish_date':fields.DateTime(dt_format='iso8601'), 'video':fields.String(), 'tags':fields.List(fields.Nested(tag_fields)), 'photos':fields.List(fields.Nested(photo_fields)), 'user':fields.Nested(user_fields) } class PostApi(Resource): @marshal_with(post_fields) def get(self,post_id=None): if post_id: post=Post.query.get(post_id) print(post.photos) if not post: abort(404) return post else:
from sqlalchemy import exc from .. import validators from ..models import Proxy new_proxy_parser = reqparse.RequestParser() new_proxy_parser.add_argument( 'ip_address', type=validators.ip_address, required=True, location='json', ) proxy_fields = OrderedDict([('ip_address', fields.String), ('ip_type', fields.Integer), ('date_created', fields.DateTime('iso8601')), ('last_checked', fields.DateTime('iso8601')), ('last_succesful_check', fields.DateTime('iso8601')), ('updated_since_synced', fields.Boolean), ('online', fields.Boolean)]) class Proxies(Resource): @marshal_with(proxy_fields) def get(self, ip_address=None): """ View listing of all available proxies """ if ip_address: return Proxy.get_or_404(ip_address)
author_fields = { "id": fields.Integer(), "username": fields.String(), "gravatar": fields.String() } post_fields = { "id": fields.Integer(), "link": fields.String(attribute=lambda p: url_for( "main.article", post_id=p.id, _external=True)), "body": fields.String(), "timestamp": fields.DateTime(dt_format="iso8601"), "author": fields.Nested(author_fields), "title": fields.String(), "summary": fields.String(), "last_edit": fields.DateTime(dt_format="iso8601"), "count": fields.Integer(), "category_name": fields.String(attribute=lambda p: p.category.name if p.category else ""), "tags": fields.List(fields.Nested(tag_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)
class RoleItem(fields.Raw): def format(self, value): return Role.query.get_or_404(value).name class AvatarItem(fields.Raw): def output(self, key, obj): return obj.avatar(128) resource_fields = { 'id': fields.Integer, 'username': fields.String, 'name': fields.String(default='Common User'), 'email': fields.String, 'timestamp': fields.DateTime(dt_format='rfc822', attribute='member_since'), 'role_name': RoleItem(attribute='role_id'), '_links': { 'avatar': AvatarItem, 'self': fields.Url('api_v2.user') } } # User: shows a single user item and lets you delete a user item class UserAPI(Resource): method_decorators = [token_auth.login_required ] # applies to all inherited resources @marshal_with(resource_fields) def get(self, id):
from flask_restful import reqparse, abort, Resource, fields, marshal_with parser_user = reqparse.RequestParser() parser_user.add_argument('first_name') parser_user.add_argument('last_name') parser_user.add_argument('birthdate') parser_user.add_argument('email') parser_user.add_argument('password') parser_user.add_argument('type') parser_user.add_argument('rating') user_fields = { 'id': fields.Integer, 'first_name': fields.String, 'last_name': fields.String, 'birthdate': fields.DateTime(dt_format='iso8601'), 'email': fields.String, 'password': fields.String, 'type': fields.String, 'rating': fields.Float } class Database(object): def get_session(self): """Return new session Returns: [Session] -- [Return a new session] """ connection = os.environ.get("DATABASE_URL") engine = create_engine(connection)
return {'message': '重置成功'}, 200 user_fields = { 'id': fields.Integer, 'first_name': fields.String(default=''), 'last_name': fields.String(default=''), 'nickname': fields.String(default=''), 'email': fields.String(default=''), 'mobile': fields.String(default=''), 'github_login': fields.String(default=''), 'github_name': fields.String(default=''), 'github_email': fields.String(default=''), 'google_name': fields.String(default=''), 'google_email': fields.String(default=''), 'last_login_at': fields.DateTime(dt_format='iso8601'), 'created_at': fields.DateTime(dt_format='iso8601') } @api.resource('/profile') class Profile(Resource): @marshal_with(user_fields) @login_required def get(self): return current_user @marshal_with(user_fields) @login_required def patch(self): parser = reqparse.RequestParser()
from flask import g from flask_restful import Resource, reqparse, fields, marshal_with from dateutil import parser from flask_jwt_extended import jwt_required from .revisions import revision_fields from ... import db from ...models import Revision, CinebenchR15Result cinebenchr15result_fields = { 'id': fields.Integer, 'result_date': fields.DateTime(dt_format='iso8601'), 'cpu_cb': fields.Integer(default=None), 'opengl_fps': fields.Integer(default=None), 'revision': fields.Nested(revision_fields), 'uri': fields.Url('.cinebenchr15result', absolute=True) } class CinebenchR15ResultListAPI(Resource): @marshal_with(cinebenchr15result_fields, envelope='cinebenchr15results') def get(self): return CinebenchR15Result.query.order_by( CinebenchR15Result.cpu_cb.desc()).all() class CinebenchR15ResultAPI(Resource): def __init__(self): self.reqparse = reqparse.RequestParser() self.reqparse.add_argument('result_date', type=str, location='json') self.reqparse.add_argument('cpu_cb', type=int, location='json') self.reqparse.add_argument('opengl_fps', type=int, location='json')
veh_parse.add_argument('descripcion', required=True) veh_parse.add_argument('color', required=True) veh_parse.add_argument('fecha_v', required=True) veh_parse.add_argument('serial_m', required=True) veh_parse.add_argument('serial_c', required=True) veh_parse.add_argument('fk_mod', required=True) veh_parse.add_argument('fk_sucursal', required=True) veh_fields = { 'id': fields.Integer, 'placa': fields.String, 'cap_c': fields.Float, 'peso': fields.Float, 'descripcion': fields.String, 'color': fields.String, 'fecha_v': fields.DateTime('iso8601'), 'serial_m': fields.String, 'serial_c': fields.String, 'modelo': fields.String, 'fk_sucursal': fields.String } modelos_field = {'id': fields.Integer, 'nombre': fields.String} class VehiculoList(Resource): @jwt_required def get(self): try:
from app.utils.auth import auth_required, event_admin_required from app import LOGGER from app import db from app.utils import errors from app.utils import misc def _extract_status(outcome): if not isinstance(outcome, Outcome): return None return outcome.status.name outcome_fields = { 'id': fields.Integer, 'status': fields.String(attribute=_extract_status), 'timestamp': fields.DateTime(dt_format='iso8601'), } user_fields = { 'id': fields.Integer, 'email': fields.String, 'firstname': fields.String, 'lastname': fields.String, 'user_title': fields.String } outcome_list_fields = { 'id': fields.Integer, 'status': fields.String(attribute=_extract_status), 'timestamp': fields.DateTime(dt_format='iso8601'), 'user': fields.Nested(user_fields),
from flask_restful import Resource from flask_restful import reqparse, fields, marshal_with from datetime import datetime from model import challenge_datasource as datasource import date_util as dateutil # marshaller day_field = { 'day': fields.DateTime(dt_format='rfc822'), 'done': fields.Boolean } challenge_fields = { 'id': fields.Integer, 'title': fields.String, 'start_date': fields.DateTime(dt_format='rfc822'), 'end_date': fields.DateTime(dt_format='rfc822'), 'days': fields.List(fields.Nested(day_field)) } # request parser parser = reqparse.RequestParser() parser.add_argument('title', location = 'json', help = 'Challenge title') parser.add_argument('start_date', type = lambda x: datetime.strptime(x, '%Y-%m-%d'), location = 'json', help = 'Challenge start date') parser.add_argument('end_date', type = lambda x: datetime.strptime(x, '%Y-%m-%d'), location = 'json', help = 'Challenge end date') class Challenges(Resource): @marshal_with(challenge_fields, envelope='challenges') def get(self): # return all challenges return datasource.challenges