from app import api from flask import render_template import flask.views from flask import Flask, request, jsonify import intent_classify from intent_classify import classify_intent import json from flask_restplus import Resource, fields namespace = api.namespace('classify_intent', description="Detect intent of the text.") single_model = api.model('Input Single Text Model', { 'text': fields.String, 'lang': fields.String }) multiple_model = api.model('Input Multiple Texts Model', {'texts': fields.List(fields.Nested(single_model))}) @namespace.route('/') class IntentClassify(Resource): @api.doc(responses={200: 'OK'}) def get(self): return """This service gives you an intent detecting functionality. Use post query with thr following structure: {'text': <...>, 'lang': <...>} or use JSON key 'texts': [<array of texts>].""" @api.doc(responses={200: 'OK', 400: 'Bad Request'}) @api.expect(multiple_model) def post(self): data = json.loads(request.data)
from app import api,db from util.globals import * from util.models import * from flask_restplus import Resource, abort, reqparse, fields from flask import request auth = api.namespace('auth', description='Authentication Services') @auth.route('/login', strict_slashes=False) class Login(Resource): @auth.response(200, 'Success',token_details) @auth.response(400, 'Missing Username/Password') @auth.response(403, 'Invalid Username/Password') @auth.expect(login_details) @auth.doc(description=''' This is used to authenticate a verified account created through signup. Returns a auth token which should be passed in subsequent calls to the api to verify the user. ''') def post(self): if not request.json: abort(400,'Malformed Request') (un,ps) = unpack(request.json,'username','password') if not db.exists('USER').where(username=un,password=ps): abort(403,'Invalid Username/Password') t = gen_token() db_r = db.update('USER').set(curr_token=t).where(username=un) db_r.execute() return { 'token': t }
from app import api version = "1.0" ver = "v1" ns = api.namespace('Reports', description='UniParthenope csv reports for PTA/Admin') from app.apis.export.v1.export_v1 import ReportsCSV ns.add_resource(ReportsCSV, '/v1/getCSV', methods=['POST'])
from app import db, api, authorization from sqlalchemy import or_, and_ from flask_restplus import Resource from datetime import datetime from flask import abort, request, g from app.user.decorators import login_required from app.user.models import User from models import Message from serializers import message_model from config import NUM_PAGES messages_api = api.namespace( 'messages', description='For sending and showing messages between users') @messages_api.route('') class UserMessage(Resource): @messages_api.expect(authorization, message_model) @login_required def post(self): """ For sending a new message through HTTP """ data = api.payload receiver_id = data.get("receiver_id") content = data.get("content") if not User.query.get(receiver_id): abort(400) message = Message(content=content, receiver_id=receiver_id, sender=g.user,
from app import api,db from util.globals import * from util.models import * from flask_restplus import Resource, abort, reqparse, fields from PIL import Image from io import BytesIO import base64 import time from flask import request dummy = api.namespace('dummy', description='Dummy Post Services for testing') @dummy.route('/post', strict_slashes=False) class Dummy_Post(Resource): @dummy.response(200, 'Success', post_id_details) @dummy.response(400, 'Malformed Request / Image could not be processed') @dummy.expect(new_post_details) @dummy.doc(description=''' Identical to POST /post but doesn't require any authentication Allows you to act as a "Anon" user. ''') def post(self): j = request.json u = get_dummy_user() u_username = u[1] if not j: abort(400, 'Malformed request') (desc,src) = unpack(j,'description_text','src') if desc == "" or src == "": abort(400, 'Malformed request') try:
import base64 from app import api, Config from flask_restplus import Resource from functools import wraps from flask import request, g from app.models import OtherUser url = "https://uniparthenope.esse3.cineca.it/e3rest/api/" ns = api.namespace('technologyAdvising') def token_required_general(f): @wraps(f) def decorated(*args, **kwargs): token = None if 'Authorization' in request.headers: token = request.headers['Authorization'] if not token: return {'message': 'Token is missing.'}, 401 _token = token.split()[1] g.response = auth(_token) g.status = g.response[1] return f(*args, **kwargs) return decorated
from app import api,db from util.globals import * from util.models import * from flask_restplus import Resource, abort, reqparse, fields from PIL import Image from io import BytesIO import base64 import time from flask import request posts = api.namespace('post', description='Post Services') @posts.route('/', strict_slashes=False) class Post(Resource): @posts.response(200, 'Success', post_id_details) @posts.response(403, 'Invalid Auth Token') @posts.response(400, 'Malformed Request / Image could not be processed') @posts.expect(auth_details,new_post_details) @posts.doc(description=''' Lets you make a new post, both a description and src must be supplied. The Supplied description test must be non empty and the image be a valid png image encoded in base 64 (only png is supported at the present moment) If either of these is not met the request is considered malformed. Note the src just needs to be the base64 data, no meta data such as 'data:base64;' is required. Putting it in will make the data invalid. Returns the post_id of the new post on success. ''') def post(self): j = request.json u = authorize(request) u_username = u[1]
from app import db, api, authorization from flask_restplus import Resource from flask import abort, g from app.user.models import User from app.user.decorators import admin_required from models import Tag from serializers import tag_model tag_api = api.namespace('tags', description='For showing posts and users Tags') @tag_api.route('') class Tags(Resource): def get(self): """ Returns all tags. """ return {'elements': [element.to_json() for element in Tag.query.all()]} @tag_api.expect(authorization, tag_model) @admin_required def post(self): """ Adds a new tag. """ data = api.payload name = data.get('name') if Tag.query.filter_by(name=name).first() is not None: return {'message': "The tag\'s name already exists!"}, 400
from app import api from utils.wordeater_api import ApiResponse from cerberus import Validator from config import API_PATH, ENVELOPE_DATA from services.service_locator import ServiceLocator from decorators.authenticate import expose from models import translation_schema, translation_fields, translation_input_fields, translation_detect_fields from errors import ServerErrors from logger import error __author__ = 'Glebov Boris' translations_ns = api.namespace(name='Translations', description="Requests related with translations", path=API_PATH) class TranslationResource(Resource): def __init__(self, api, *args, **kwargs): Resource.__init__(self, api, *args, **kwargs) self.ss = ServiceLocator.resolve(ServiceLocator.SESSIONS) self.ts = ServiceLocator.resolve(ServiceLocator.TRANSLATIONS) @translations_ns.route('/translations/translate/', endpoint='translate') class TranslationsTranslateAPI(TranslationResource): @expose @api.doc(body=translation_input_fields) @api.marshal_with(translation_fields, envelope=ENVELOPE_DATA, code=200) def post(self):
from services.users import UserService from services.groups import GroupService from domain.model import db from pydash import py_ from mongokit import ObjectId # Mappers from api.mapper.group_mapper import group_to_dict from api.mapper.card_mapper import card_to_dict_for_learn from logger import logger __author__ = 'Warlock' groups_ns = api.namespace(name='Groups', description="Requests for page groups", path=API_PATH) def get_user(): us = UserService(db) current_user = session['user'] #user = us.get(current_user['login']) user = us.get(u'warlock') return user @groups_ns.route('/learn/groups/', endpoint='groups_for_learns') class GroupsForLearnAPI(Resource): def get(self): u"""
# coding=utf-8 from flask.ext.restplus import Resource from app import api from config import API_PATH from services.cards import CardService __author__ = 'Warlock' cards_ns = api.namespace(name='Cards', description="Requests for page words", path=API_PATH) @cards_ns.route('/list/', endpoint='cards') class CardsAPI(Resource): def get(self): u""" Get viewmodel for Words page :return: """ return { 'data': [{'id':'123', 'name': '12'}] }
from utils.wordeater_api import ApiResponse from app import api from models import user_schema, user_fields, user_input_fields, user_list_fields, user_signin_fields, user_signin_schema,\ user_sigin_response_fields, check_user_fields, check_params_schema, check_user_input_fields from services.service_locator import ServiceLocator from services.exceptions import LoginAlreadyExists, EmailAlreadyExists from decorators.authenticate import allow_debug_only from logger import error __author__ = 'Glebov Boris' users_ns = api.namespace(name='Users', description="Requests related with users", path=API_PATH) @users_ns.route('/users/', endpoint='users/') class UsersAPI(Resource): @allow_debug_only @api.marshal_with(user_list_fields, envelope=ENVELOPE_DATA, as_list=True) def get(self): """ Returns list of users :return: list of users """ us = ServiceLocator.resolve(ServiceLocator.USERS) users = list(us.list())
from app import api,db from util.globals import * from util.models import * from flask_restplus import Resource, abort, reqparse, fields from flask import request user = api.namespace('user', description='User Information Services') @user.route('/', strict_slashes=False) class User(Resource): @user.response(200, 'Success', user_details) @user.response(403, 'Invalid Auth Token') @user.response(400, 'Malformed Request') @user.expect(auth_details) @user.param('id','Id of user to get information for (defaults to logged in user)') @user.param('username','username of user to get information for (defaults to logged in user)') @user.doc(description=''' Gets the information for the supplied user, if neither id nor username is specified the user corresponding to the supplied auth token's information is returned. If both are supplied the id is used first and on failure the username is used. If all supplied forms of identification are invalid the request is considered malformed. The response object contains a list of user_ids of the user following the target user and the total number of people who follow the target user. These are contained in the variables following and followed_num respectively. The response also contains the list of posts by the target user referenced by their post id. use the GET /post to retrive the entire post ''') def get(self): u = authorize(request) u_id = request.args.get('id',None) username = request.args.get('username',None)
from app import api version = "1.0" ver = "v1" ns = api.namespace('Access', description='UniParthenope access operations') from app.apis.access.v1.access_v1 import Access, getCompleteCSV, CovidAlert, Certification ns.add_resource(Access, '/v1/classroom', methods=['GET', 'POST']) ns.add_resource(Certification, '/v1/covidStatement', methods=['GET', 'POST']) ns.add_resource(getCompleteCSV, '/v1/getCSV', methods=['GET']) ns.add_resource(CovidAlert, '/v1/covidStatementMessage', methods=['GET'])
from app import api from mongokit import ObjectId from config import API_PATH, ENVELOPE_DATA from cerberus import Validator from services.service_locator import ServiceLocator from models import card_list_fields, card_schema, card_fields, card_input_fields from decorators.authenticate import expose from errors import ServerErrors, CardsErrors from logger import error __author__ = 'Warlock' cards_ns = api.namespace(name='Cards', description="Requests related with cards", path=API_PATH) class CardsResource(Resource): def __init__(self, api, *args, **kwargs): Resource.__init__(self, api, *args, **kwargs) self.ss = ServiceLocator.resolve(ServiceLocator.SESSIONS) self.cs = ServiceLocator.resolve(ServiceLocator.CARDS) self.gs = ServiceLocator.resolve(ServiceLocator.GROUPS) @cards_ns.route('/cards/', endpoint='cards') class CardsAPI(CardsResource): @expose @api.marshal_with(card_list_fields, envelope=ENVELOPE_DATA, as_list=True) def get(self):
from bs4 import BeautifulSoup from flask import g, request from app import api, Config from flask_restplus import Resource, fields import requests from datetime import datetime import sys import json import traceback from babel.numbers import format_currency from concurrent.futures import ThreadPoolExecutor from app.apis.uniparthenope.v1.login_v1 import token_required, token_required_general url = "https://uniparthenope.esse3.cineca.it/e3rest/api/" ns = api.namespace('uniparthenope') # ------------- DEPARTMENT INFO ------------- parser = api.parser() parser.add_argument('stuId', type=str, required=True, help='User stuId') @ns.doc(parser=parser) class DepInfo(Resource): @ns.doc(security='Basic Auth') @token_required def get(self, stuId): """Get Department Information""" headers = { 'Content-Type': "application/json",
from app import api from flask_restplus import Resource, fields from flask import request from models import * from helpers import * import db auth = api.namespace('auth', description="Authentication") @auth.route('/login') class Login(Resource): @auth.response(200, 'Success') @auth.response(400, 'Missing Username/Password') @auth.response(403, 'Invalid Username/Password') @auth.expect(login_details) @auth.doc(description=''' This is used to authenticate a verified account created through signup. ''') def post(self): conn = db.get_db() j = get_request_json() users = conn['users'] data = dict(username=j['username'], password=j['password']) results = users.find_one(username=j['username'], password=j['password']) if (not results): auth.abort(400, 'Username or password incorrect', result='none')
from app import api from util.models import * from util.helper import * from util.checkers import * from flask_restplus import Resource, fields, abort from flask import request import sqlite3 recommend = api.namespace('recommend', description='ingredient recommendation') @recommend.route('/get', strict_slashes=False) class Recommend(Resource): @recommend.response(200, 'Success', ingredient_list_model) @recommend.response(400, 'Malformed Request') @recommend.expect(ingredients_tags_model) @recommend.doc(description=''' takes in a list of ingredients, returns a list of ingredients that do not match the ingredients passed in The returned list of ingredients are recommendations for narrowing down recipes that the user would like ''') def post(self): r = request.json if not r: abort(400, 'Malformed Request') # search for list of recipes based on ingredients + tags # get recipe_ids from list of recipes # get list of ingredients associated with the recipe_ids # for each recipe, see if there are ingredients to recommend # go through all recipes or until 5 recommded is reached
""" Constants """ EMAIL_SENT = "Email is sent to customer service." # """ Message parser """ # _message_parser = reqparse.RequestParser() # _message_parser.add_argument( # "user_email", required=True, # ) # _message_parser.add_argument( # "message", required=True, # ) """ Create namespace """ contactus_ns = api.namespace("contactus", description="Send message API") ContactUsMessageSchema = contactus_ns.model( "ContactUsMessageSchema", { "user_name": fields.String(required=True), "user_email": fields.String(required=True), "subject": fields.String(required=True), "order_id": fields.String, "message": fields.String(required=True), }, ) """ Contactus Resource """
######################################################################## from flask import send_from_directory from flask_restplus import Resource from app import cache, api from app.Buchung import Buchung from app.models import m_itinerary, m_bookingrequest, m_booking, m_form_request from app.Reiseplan import Reiseplan from app.Complaint import Complaint from os.path import basename, dirname ######################################################################## # namespaces ######################################################################## ns_itineraries = api.namespace('itineraries', description='Operations related to itineraries') ns_bookings = api.namespace('bookings', description='Operations related to bookings') ns_form = api.namespace( 'forms', description='Operations related to Fahrgastrechte forms') ######################################################################## # routes ######################################################################## @ns_itineraries.route('/<auftragsnummer>') @api.doc(params={'auftragsnummer': 'a 6-character reference number'}) class ReferenceNumber(Resource): @api.response(404, 'itinerary not found') @ns_itineraries.marshal_with(m_itinerary)
) AddressSchema = api.model( "AddressSchema", { "id": fields.Integer, "name": fields.String, "address1": fields.String, "address2": fields.String(default=""), "city": fields.String, "country": fields.String, "zip_code": fields.String, }, ) """ Create Namespace """ addresses_ns = api.namespace("addresses", description="Addresses API") address_ns = api.namespace("address", description="Address API") """ Addresses Resource """ @addresses_ns.route("/<int:user_id>", doc={"params": { "user_id": "id of a user" }}) class AddressList(Resource): @classmethod @addresses_ns.doc("list_addresses") @addresses_ns.marshal_list_with(AddressSchema) def get(cls, user_id): addresses = AddressModel.query.filter_by(user_id=user_id) return addresses, 200
from flask_restplus import Resource, fields from app.models import ProductBrand as BrandModel from app import api from . import INTERNAL_ERROR brand_ns = api.namespace("brands", description="Brand API") BrandSchema = brand_ns.model( "BrandSchema", { "name": fields.String, "slug": fields.String, "total_products": fields.Integer }, ) @brand_ns.route("") class Brand(Resource): @classmethod @brand_ns.doc("list_brands") @brand_ns.marshal_list_with(BrandSchema, envelope="brand_list") def get(cls): try: brands = BrandModel.query.all() except Exception as ex: print(ex) return {"message": INTERNAL_ERROR}, 500 return brands, 200
339: "Bulla", 340: "Coldstream", 341: "Hopetoun Park", 342: "Cranbourne West", 343: "Eynesbury", 344: "Fawkner Lot", 345: "Ferny Creek", 346: "Wandin North", 347: "Kalkallo", 348: "Menzies Creek" } SECRET_KEY = 'Abracadabra' expires_in = 300 get_auth = AuthenticationToken(SECRET_KEY, expires_in) house = api.namespace('house', description='house price prediction') @house.route('/data', strict_slashes=False) class House(Resource): @house.response(200, 'Success') @house.response(400, 'Invalid/Missing parameters') @house.response(401, 'Invalid/Missing token') @house.expect(house_details) @house.doc(description=''' Use this endpoint to get the prediction of price with the features given by user, a valid token should also be provided to keep the stability of the API ''') def post(self): j = get_request_json() (tk, sb, rm, tp, dis, car, ba,
from app import api from flask_restplus import Resource, fields import lib.shovel_service as shovel_service shovel_route = api.namespace('Shovel', description='Shovel to register and unregister \ a compute node from RackHD with Ironic') # models register_model = api.model( 'Register', { 'uuid': fields.String(required=True, description='rackhd node id'), 'driver': fields.String(required=True, description='ironic driver'), 'ipmihost': fields.String(required=False), 'ipmiuser': fields.String(required=False), 'ipmipass': fields.String(required=False), 'name': fields.String(required=True, description='node name'), 'kernel': fields.String(required=True), 'ramdisk': fields.String(required=True), 'port': fields.String(required=True) }) @shovel_route.route('/register') class register(Resource): @shovel_route.expect(register_model) def post(self): '''register RackHd node with Ironic''' return shovel_service.register(api.payload)
from app import api #login route login_route = api.namespace('login', description='User Authentication') #register route register_route = api.namespace('register', description='User Register') # users route users_route = api.namespace('users', description='User CRUD') # posts route posts_route = api.namespace('posts', description='Posts CRUD') # player route players_route = api.namespace('players', description='Player CRUD') # teams route teams_route = api.namespace('teams', description='Team CRUD') # teams_players route teams_players_route = api.namespace('teams-players', description='Teams and Players CRUD')
from flask import Flask, Blueprint from flask_restplus import Api, Namespace, Resource from app import api from .test import Request_data_vaccination import json from .services import get_data, get_data_depistage, get_data_vaccination france_routes = Blueprint('france', __name__, url_prefix='/france') france_routes_api = api.namespace('France', description="France operations") @france_routes_api.route("/recovered/") class RecoveredList(Resource): def get(self): """ returns a list of books """ return get_data() @france_routes_api.route("/death/") class DeathList(Resource): def get(self): """ returns a list of books """ return {"response": 'test data'} @france_routes_api.route("/confirmed/") class ConfirmedList(Resource):
from app import api from util.models import * from util.helper import * from util.checkers import * from flask_restplus import Resource, fields, abort from flask import request import sqlite3 recipe = api.namespace('recipe', description='Recipe information') @recipe.route('/searchName', strict_slashes=False) class searchName(Resource): @recipe.response(200, 'Success', recipe_list_model) @recipe.response(400, 'Malformed Request') @recipe.expect(recipe_name_tags_model) @recipe.doc(description=''' Returns a list of all recipes that matches the tags passed in and has the search term passed in If no tags are passed in, or no search queries are passed in, returns all recipes in the database. ''') def post(self): r = request.json if not r: abort(400, 'Malformed Request') # Getting the tags from the payload tags = get_list(r, 'tags', 'tag')
from flask import request, jsonify from flask_restx import Resource, abort, reqparse, fields from flask_jwt_extended import get_jwt_claims, jwt_required from app import api, db from db.stats_db import stats_DB import model.stats_model as stats_model stats_db = stats_DB(db) stats = api.namespace('stats', description='Stats Route') @stats.route('/sales') class Sales(Resource): @jwt_required @stats.response(200, 'Success', model=stats_model.sales_response_model) @stats.response(500, 'Something went wrong') def get(self): # Make sure user is a manager role = get_jwt_claims().get('role') if db.get_staff_title(role) != 'Manage': abort(400, 'User is not a manager') # Amount of sales for each item item_sales = stats_db.get_menu_item_sales() if (item_sales is None): abort(500, 'Something went wrong') # Sum up revenues total_revenue = 0
from app import api from util.models import * from util.helper import * from util.checkers import * from flask_restplus import Resource, fields, abort from flask import request import sqlite3 ingredients = api.namespace('ingredients', description='adding ingredients') @ingredients.route('/add', strict_slashes=False) class Add(Resource): @ingredients.response(200, 'Success') @ingredients.response(400, 'Malformed Request') @ingredients.response(403, 'ingredient already exists') @ingredients.expect(ingredient_detail_model) @ingredients.doc(description=''' Takes in category, and ingredient_name Sending the ingredient into this endpoint will result in the ingredient being added to the database. Once added to the database, the ingredient will show up when searched for ''') def post(self): r = request.json ### TODO if not r: abort(400, 'Malformed Request') check_ingredients_category(r) ing_name = r['name'].lower()
from app import db, api, authorization from flask_restplus import Resource from flask import abort, g from app.tag.models import Tag from models import Post from forms import PostForm from serializers import post_model from app.user.decorators import login_required from datetime import datetime from config import POSTS_PER_PAGE import uuid post_api = api.namespace('posts', description='For sending and showing users posts') @post_api.route('') class Posts(Resource): @post_api.expect(authorization, post_model) @login_required def post(self): """ Adds a new post """ data = api.payload tags = data.get('tags') if not tags: abort(400, {"Tags": ["Les tags sont necessaire!"]}) form = PostForm.from_json(data) if form.validate(): title = data.get('title') content = data.get('content') post = Post(id=uuid.uuid4().hex,title=title.lower(), content=content, user=g.user,\
from app import api, db from util.globals import * from util.models import * from flask_restplus import Resource, abort, reqparse, fields from PIL import Image from io import BytesIO import base64 import time from flask import request dummy = api.namespace('dummy', description='Dummy Endpoints for testing') def shrink(src): size = (150, 150) im = Image.open(BytesIO(base64.b64decode(src))) im.thumbnail(size, Image.ANTIALIAS) buffered = BytesIO() im.save(buffered, format='PNG') return base64.b64encode(buffered.getvalue()).decode("utf-8") @dummy.route('/post', strict_slashes=False) class Dummy_Post(Resource): @dummy.response(200, 'Success', post_id_details) @dummy.response(400, 'Malformed Request / Image could not be processed') @dummy.expect(new_post_details) @dummy.doc(description=''' Identical to POST /post but doesn't require any authentication Allows you to act as a "Anon" user. ''')
import os import datetime import random, string import werkzeug.security from flask import render_template, flash, redirect, request, url_for, jsonify from app import app, db, api from app.models import User, Registrations from app.farer import auth_token from config import Config from werkzeug.utils import secure_filename from werkzeug.urls import url_parse from flask_restplus import Resource, Api from google.oauth2 import id_token from google.auth.transport import requests reg = api.namespace('reg', description="Registration management") # Not in usage. Need to decide the state @reg.route('/workshop/<int:id>') class workshop_reg(Resource): # API Params: JSON(Authorization, [Standard]) # Standard: IP, Sender ID # Returns: JSON(Registration state) def get(self, id): try: auth_header = auth_token(request) #u = User.query.filter_by(vid = User.decode_auth_token(auth_header)).first() w = Registrations.query.filter_by(eid=id) if w is not None: responseObject = {
import json from app import api, db from flask_restplus import Resource, abort, reqparse, fields from flask import request, jsonify from util.models import * from util.authorize import authorize, authorize_access trip = api.namespace('trip', description='User trips endpoint') @trip.route('', strict_slashes=False) @trip.doc(security='authtoken') class Trip(Resource): @trip.response(200, 'Success', MODEL_trip_uuid) @trip.response(400, 'Malformed request') @trip.response(403, 'Invalid authorization') @trip.doc(description='Store user trip') @trip.expect(MODEL_trip_payload) def post(self): email = authorize(request) # Get payload and set variables content = request.get_json() info = content.get('info') if info is None: abort(400, 'Required info field is empty') description = info.get('description') city = info.get('city')
from flask import request, jsonify, send_file, make_response from app import app, api import os from flask_restplus import Resource, reqparse import werkzeug import tempfile from wireviz import wireviz from app import plant_uml_decoder file_upload = reqparse.RequestParser() file_upload.add_argument('yml_file', type=werkzeug.datastructures.FileStorage, location='files', required=True, help='YAML file') ns = api.namespace('', description='wireviz server') @ns.route('/render/') class Render(Resource): @api.expect(file_upload) @ns.produces(['image/png', 'image/svg+xml']) def post(self): """ """ args = file_upload.parse_args() try: file_temp = tempfile.TemporaryFile() args['yml_file'].save(file_temp) filename = os.path.splitext( os.path.basename(os.path.normpath(
from app import api from flask_restplus import Resource, fields from ..models import Bucketlist, db, User, Bucketitems from flask import request, abort from .parsers import pagination_arg bucket = api.namespace('bucketlists', description="Bucketlist Endpoints") bucket_item = api.model( 'bucket_item', { 'id': fields.Integer(required=True, readOnly=True), 'name': fields.String(required=True), 'date_created': fields.DateTime, 'date_modified': fields.DateTime, 'done': fields.Boolean, }) bucket_item_update = api.model( 'bucket_item_update', { 'name': fields.String(description='Name of the bucketlist item'), 'done': fields.Boolean(description='Status of the bucketlist item') }) buckett = api.model( 'Buckett', { 'id': fields.Integer(required=True, readOnly=True), 'name': fields.String(required=True, description='This is the name of the bucketlist'), 'items':
from app import api from flask_restplus import Resource, fields from flask import request from models import * from helpers import * import db tags = api.namespace('tags', description="Managing users tags") @tags.route('/<string:username>') @tags.doc(params={'username': '******'}) class Tags(Resource): @tags.response(200, 'Success') @tags.doc(description=''' Delete tag for given user ''') @tags.expect(tag_details) def delete(self, username): conn = db.get_db() j = get_request_json() table = conn['tags'] result = table.delete(username=username, tag=j['tag_name']) if (not result): tags.abort(404, "Tag '{}' not found for user '{}'".format( j['tag_name'], username), result='none')
import json from app import api from flask import Flask, Blueprint from flask_restplus import Api, Namespace, Resource from .services import get_all_data, get_all_data_by_category us_routes = Blueprint('US', __name__, url_prefix='/US') us_routes_api = api.namespace('US', description="United Statess operations") @us_routes_api.route("/") class List(Resource): def get(self): """ returns a list of books """ return json.loads(get_all_data()) @us_routes_api.route("/confirmed/<province_name>") class RecoveredList(Resource): def get(self, province_name): """ returns a list of books """ return json.loads(get_all_data_by_category('confirmed', province_name)) @us_routes_api.route("/death/<province_name>") class DeathList(Resource): def get(self, province_name):
from app import api, db from util.globals import * from util.models import * from flask_restplus import Resource, abort, reqparse, fields from PIL import Image from io import BytesIO import base64 import time from flask import request dummy = api.namespace('dummy', description='Dummy Post Services for testing') @dummy.route('/post', strict_slashes=False) class Dummy_Post(Resource): @dummy.response(200, 'Success', post_id_details) @dummy.response(400, 'Malformed Request / Image could not be processed') @dummy.expect(new_post_details) @dummy.doc(description=''' Identical to POST /post but doesn't require any authentication Allows you to act as a "Anon" user. ''') def post(self): j = request.json u = get_dummy_user() u_username = u[1] if not j: abort(400, 'Malformed request') (desc, src) = unpack(j, 'description_text', 'src') if desc == "" or src == "": abort(400, 'Malformed request')
from app import api from utils.wordeater_api import ApiResponse from cerberus import Validator from config import API_PATH, ENVELOPE_DATA from services.service_locator import ServiceLocator from decorators.authenticate import expose from models import picture_schema, picture_input_fields, picture_fields from errors import ServerErrors, PicturesErrors from logger import error __author__ = 'Glebov Boris' pictures_ns = api.namespace(name='Pictures', description="Requests related with pictures", path=API_PATH) class PictureResource(Resource): def __init__(self, api, *args, **kwargs): Resource.__init__(self, api, *args, **kwargs) self.ss = ServiceLocator.resolve(ServiceLocator.SESSIONS) self.ps = ServiceLocator.resolve(ServiceLocator.PICTURES) self.gs = ServiceLocator.resolve(ServiceLocator.GIPHY) @pictures_ns.route('/pictures/random/', endpoint='random') class PicturesRandomAPI(PictureResource): @expose @api.doc(body=picture_input_fields) @api.marshal_with(picture_fields, envelope=ENVELOPE_DATA, code=200)