class AuthorDTO: api = api.namespace('authors', description='Operations related to authors.') base = api.model( "Author_Base", { 'name': fields.String(description='The name of the author.'), }) create = api.clone( "Author_Create", base, { 'series_ids': fields.List( fields.Integer(required=False, description="The author's series.")) }) update = api.clone('Author_Update', create, { 'id': fields.Integer(description='The ID of the book.'), }) fk_books = api.model( "Author_Books", { 'id': fields.Integer(description='The ID of the book.'), 'title': fields.String(description='The title of the book.'), 'description': fields.String(required=True, description='The description of the book.'), }) fk_series = api.model( "Author_Books", { 'id': fields.Integer(description='The ID of the series.'), 'title': fields.String(required=True, description='The title of the series.'), 'description': fields.String(required=True, description='The description of the series.') }) list = api.model( 'Author_List', { 'id': fields.Integer(description='The ID of the author.'), 'name': fields.String(description='The name of the author.'), 'books': fields.Nested(fk_books), 'series': fields.Nested(fk_series) }) query = api.model( 'Author_Query', { 'items': fields.List(fields.Nested(list)), 'total': fields.Integer(), 'page': fields.Integer(), 'per_page': fields.Integer() })
class GenreDTO: api = api.namespace('genres', description='Operations related to genres.') base = api.model( 'Genre_Base', { 'name': fields.String(required=True, description='The name of the genre.'), }) create = api.clone( 'Genre_Update', base, { 'books_ids': fields.List( fields.Integer(required=False, description="The genre books.")), }) update = api.clone( 'Genre_Create', create, { 'id': fields.Integer(description='The ID of the genre.'), }) fk_books = api.model( 'Genre_Books', { 'id': fields.Integer(description='The ID of the book.'), 'title': fields.String(description='The title of the book.'), }) list = api.clone( 'Genre_List', base, { 'id': fields.Integer(description='The ID of the genre.'), 'books': fields.Nested(fk_books) }) query = api.model( 'Genre_Query', { 'items': fields.List(fields.Nested(list)), 'total': fields.Integer(), 'page': fields.Integer(), 'per_page': fields.Integer() })
from main import api,fields,Resource, create_access_token from models.usersmodel import UserModel,user_schema,users_schema from werkzeug.security import generate_password_hash #Creating Namespaces ns_registration=api.namespace('signup',description="signup Handler") ns_userLogin=api.namespace('login',description="Login Handler") #Models # Sign up model signup_model=api.model('signup',{ "full_name":fields.String(), "email":fields.String(), "password":fields.String() }) # Sign in model login_model=api.model('loginCredentials',{ "email":fields.String(), "password":fields.String()}) @ns_userLogin.route('') class login(Resource): # pass ... @api.expect(login_model) def post(self): """Use this to authenticate users""" data=api.payload if UserModel.check_email_exist(data["email"]): if UserModel.validate_password(data["email"],data["password"]):
from main import api, Resource, fields from models.usermodel import UserModel, user_schema, users_schema ns_users = api.namespace('users', description='all tasks regarding users') user_model = api.model('User', { 'full_name': fields.String(), 'email': fields.String(), 'password': fields.String() }) @ns_users.route('') class UsersList(Resource): def get(self): '''return a list of users''' return users_schema.dump(UserModel.fetch_all()) @ns_users.route('/<int:_id>') class Users(Resource): def get(self, _id): '''Retrieve a user by id''' user = UserModel.fetch_by_id(_id) return user_schema.dump(user) def delete(self, _id): '''delete a user by id''' user = UserModel.fetch_by_id(_id) if user: user.delete_from_db() return {'message': 'user deleted successfully'}
from flask_restx import Resource, fields from Models.landlord import LandlordModel, landlords_schema, landlord_schema from main import api landlord_namespace = api.namespace( 'Landlords', description='This Endpoint deals with all operations dealing with landlords' ) landlord_model = api.model('LANDLORD', { "name": fields.String(), "email": fields.String(), "phone": fields.Integer() }) @landlord_namespace.route('') class LandlordList(Resource): @classmethod def get(cls): '''Get a list of landlords in the system''' landlords = LandlordModel.fetch_all() if landlords: return landlords_schema.dump(landlords) else: return {'message': 'there are no landlords in the system'}, 404 @classmethod @api.expect(landlord_model) def post(cls): '''Add a landlord to the list of landlords in the system''' data = api.payload
class BookDTO: api = api.namespace('books', description='Operations related to books.') base = api.model( 'Book_Base', { 'title': fields.String(required=True, description='The title of the book.'), 'description': fields.String(required=True, description='The description of the book.'), 'start_date': fields.DateTime(description='The start date of the reading.'), 'end_date': fields.DateTime(description='The end date of the reading.') }) create = api.clone( 'Book_Update', base, { 'genre_ids': fields.List(fields.Integer(required=False)), 'author_id': fields.Integer(required=True, description="The book's author."), 'series_id': fields.Integer(required=False, description="The book's series.") }) update = api.clone('Book_Create', create, { 'id': fields.Integer(description='The ID of the book.'), }) fk_author = api.model( 'Book_Author', { 'id': fields.Integer(description='The ID of the author.'), 'name': fields.String(description='The name of the author.'), }) fk_genre = api.model( 'Book_Genre', { 'id': fields.Integer(description='The ID of the genre.'), 'name': fields.String(description='The name of the genre.'), }) fk_series = api.model( 'Book_Series', { 'id': fields.Integer(description='The ID of the series.'), 'title': fields.String(description='The name of the series.'), 'description': fields.String(description='The description of the series.'), }) list = api.clone( 'Book_List', base, { 'id': fields.Integer(description='The ID of the book.'), 'author': fields.Nested(fk_author), 'series': fields.Nested(fk_series, allow_null=True), 'genres': fields.Nested(fk_genre) }) query = api.model( 'Book_Query', { 'items': fields.List(fields.Nested(list)), 'total': fields.Integer(), 'page': fields.Integer(), 'per_page': fields.Integer() })
from main import Resource, api, fields, create_access_token from models.usermodel import UserModel, user_schema, users_schema from werkzeug.security import generate_password_hash ns_registration = api.namespace('registration', description='User sign up') ns_login = api.namespace('login', description='Login details') login_model = api.model('Login_credentials', { 'email': fields.String(), 'password': fields.String() }) registration_model = api.model( 'Signup_credentials', { 'full_name': fields.String(), 'email': fields.String(), 'password': fields.String() }) @ns_login.route('') class Login(Resource): @api.expect(login_model) def post(self): ''' use this to authenticate users''' data = api.payload email = data['email'] if UserModel.check_if_mail_exists(email): if UserModel.check_passoword(data['password'], email): user_id = UserModel.get_user_id(email) access_token = create_access_token(identity=user_id)
from main import api, fields, Resource from models.usermodel import Users_model, user_schema, users_schema from werkzeug.security import generate_password_hash, check_password_hash from flask_jwt_extended import JWTManager,jwt_required,create_access_token,get_jwt_identity # creating namespace ns_registration = api.namespace("Register", description="Registration details") ns_login = api.namespace("Login", description="Login details") # this helps the user know hoe to input the data register_model = api.model( "User", { "fullname": fields.String(), "email": fields.String(min_length=5), "password": fields.String(), }, ) login_model = api.model( "LoginLCredentials", {"email": fields.String(), "password": fields.String()} ) @ns_login.route("") class Login(Resource): @api.expect(login_model) def post(self):
from Models.tenant import TenantModel, tenants_schema, tenant_schema from flask_restx import Resource, fields from main import api tenant_namespace = api.namespace( "Tenants", description="This Endpoint deals with all operations pertaining tenants") tenant_model = api.model( "TENANT", { "full_name": fields.String(), "email": fields.String(), # "apartment_id": fields.Integer(), # "landlord_id" :fields.Integer(), "phone_number": fields.Integer(), "identity_number": fields.Integer(), "employed": fields.Boolean(), "deposit": fields.Float(), "next_of_kin": fields.String(), "security_charges": fields.Float(), "garbage_depost": fields.Float(), }, ) @tenant_namespace.route("") class TenantsList(Resource): @classmethod def get(cls): """Get a list of all tenants in a certain apartment"""
from main import db, api, fields, Resource, jwt_required, get_jwt_identity from models.store import StoreModel, stores_scehma, store_schema from models.user import UserModel store_namespace = api.namespace( "stores", description="This Endpoint deals with all operations pertaining Stores" ) store_model = api.model("Store", {"name": fields.String()}) STORE_NOT_FOUND = "that store does not exists" OPERATION_SUCCESSFUL = " '{}' operation carried out successfully" @store_namespace.route("") class StoreList(Resource): @jwt_required @api.doc(security="apikey") def get(self): """Get a list of stores""" user_id = get_jwt_identity() user = UserModel.fetch_by_id(user_id) stores = user.stores if stores: return stores_scehma.dump(stores), 200 else: return {"message": STORE_NOT_FOUND}, 404 @api.expect(store_model) @jwt_required @api.doc(security="apikey") def post(self):
from flask_restx import Resource, fields from main import api from Models.apartment import ApartmentModel, apartment_schema, apartments_schema from Models.house import houses_schema apartment_namespace = api.namespace('Apartments', description='This endpoint deals with all operations pertaining apartments') apartment_model = api.model('APARTMENT', { "title" :fields.String(), "location" :fields.String(), "landlord_id" :fields.Integer() }) @apartment_namespace.route('') class ApartmentList(Resource): @classmethod def get(cls): '''Get a list of all apartments under the manager''' apartments = ApartmentModel.fetch_all() houses = [] if apartments: apartment_list = apartments_schema.dump(apartments) apartment_ids = [] for apartment in apartments: apartment_ids.append(apartment.id) index = 0 while index < len(apartment_ids) - 1: apartment = ApartmentModel.fetch_by_id(apartment_ids[index]) if apartment: for house in apartment.houses:
from main import Resource, api, fields, jwt_required, get_jwt_identity from models.taskmodel import TaskModel, task_schema, tasks_schema from models.usermodel import UserModel # namespace ns_tasks = api.namespace('tasks', description='All tasks regarding tasks') # models task_model = api.model('Task', { 'title': fields.String(), 'description': fields.String() }) @ns_tasks.route('') class TasksList(Resource): @api.doc(security='apiKey') @jwt_required def get(self): """ use this ednpoint to get a list of tasks """ user_id = get_jwt_identity() user = UserModel.fetch_by_id(user_id) user_tasks = user.tasks return tasks_schema.dump(user_tasks) @api.doc(security='apiKey') @api.expect(task_model) @jwt_required def post(self): """ use this ednpoint to add a new task """ data = api.payload
from flask_restx import Resource, fields from Models.house import HouseModel, houses_schema, house_schema from main import api from Models.tenant import TenantModel from Models.apartment import ApartmentModel house_namesapce = api.namespace( "Houses", description="deals with all operations pertaining houses" ) house_model = api.model( "HOUSE", { "number_of_bedrooms": fields.Integer(), "rent": fields.Float(), "house_no": fields.String(), "occupied": fields.Boolean(), "tenant_id": fields.Integer(), "apartment_id" :fields.Integer() # "landlord_id" :fields.Integer() }, ) @house_namesapce.route("") class HouseList(Resource): @classmethod def get(cls): """Get a list of all houses in an apartment""" houses = HouseModel.fetch_all() if houses:
from main import api, fields, Resource from models.usersmodel import UserModel, user_schema, users_schema ns_users = api.namespace('users', description="Deals with User manipulations") # models user_model = api.model( 'User', { 'full_name': fields.String(), 'email': fields.String(), 'password': fields.String() }) @ns_users.route('') class Users(Resource): def get(self): """Fetch all users""" wote = UserModel.fetch_all() print(users_schema.dump(wote)) return users_schema.dump(wote) @ns_users.route("/<int:id>") class User(Resource): def get(self, id): """Fetch User by id""" msee_flani = UserModel.query.filter_by(id=id).first()
api, Resource, fields, jsonify, create_access_token, jwt_required, get_jwt_identity, create_refresh_token, jwt_refresh_token_required, get_raw_jwt, BLACKLIST, ) from models.user import UserModel, user_schema from models.confirmation import ConfirmationModel register_namespace = api.namespace( "register", description="new to our API? kidnly register here") refresh_namespace = api.namespace( "refresh", description="Refreshes user access token after a while") login_namespace = api.namespace("login", description="Registered users may login") logout_namespace = api.namespace("logout", description="logged in users may logout") register_model = api.model( "Register", { "full_name": fields.String(), "email": fields.String(), "password": fields.String(), }, )
from main import Resource, api, fields from models.user import UserModel, users_schema, user_schema users_namespace = api.namespace( "users", description="THis endpoint deals with all operations regarding users") user_model = api.model( "User", { "full_name": fields.String(), "email": fields.String(), "password": fields.String(), }, ) @users_namespace.route("") class ItemList(Resource): def get(self): """Get a list of all users""" users = UserModel.fetch_all() if users: return users_schema.dump(users) else: return {"message": "please try again later"}, 500 @users_namespace.route("/<int:id>") class User(Resource): def get(self, id: int): """ Geta a user by id"""
from main import api from flask_restx import Resource, fields register_namespace = api.namespace( 'Register', description='This endpoint deals with registering new users to the system') register_model = api.model('USER', { "full_name": fields.String(), "email": fields.String() }) @register_namespace.route('') class UserList(Resource): @classmethod def get(cls): '''Get a list of managers in the system''' pass @classmethod def post(cls): '''Add a user to the system''' pass @register_namespace.route('/<int:id>') class User(Resource): @classmethod def get(cls, id: int): '''Get a user based on their id''' pass
# coding=utf-8 from flask_restplus import Resource from main import api ns = api.namespace('management', description='A simple Back-stage management API') @ns.route('/login') class HelloWorld(Resource): @ns.param('id', 'The task identifier') def get(self): return {'hello': 'world'} @ns.param('ids', 'The task identifier') def put(self): return {'hello': 'world'}
from sqlalchemy import desc from sqlalchemy.exc import IntegrityError from auth.auth import requires_auth_with_same_user, requires_auth from main import api, logger from flask_restx import Resource, abort from flask import request from models.progress import progress_model, progress_list_model, \ all_progress_model from database.progress import Progress from database.user import User progress_ns = api.namespace('progress', description='Progress operations') @progress_ns.route('/') class ProgressList(Resource): @progress_ns.marshal_list_with(all_progress_model) @requires_auth('read:progress') def get(self, payload): """Get a list of every user's progress. Requires read:progress permission""" logger.info(f"GET request to all progress list") progress_list = Progress.query.all() response = {
from main import api, fields, Resource, jwt_required, get_jwt_identity from models.tasksmodel import TaskModel, task_schema, tasks_schema from models.usersmodel import UserModel ns_tasks = api.namespace('tasks', description="All Task Operations") # models Documenting the nature of your Payload task_model = api.model( 'Task', { 'title': fields.String(), 'description': fields.String(), 'completed': fields.String() }) @ns_tasks.route('') class Tasks(Resource): @jwt_required def get(self): """Use this Endpoint to get all Tasks""" uid = get_jwt_identity() user = UserModel.get_userby_id(uid) user_tasks = user.tasks return tasks_schema.dump(user_tasks), 200 @api.expect(task_model) @jwt_required def post(self): """Use this Endpoint to add all Tasks""" data = api.payload
from time import time import traceback from flask_restx import Resource from flask import make_response, render_template from main import api from models.confirmation import ConfirmationModel, confirmation_schema from models.user import UserModel from libs.mailgun import MailgunException confirm_namespace = api.namespace( "confirm", description="confirm newly-registered users" ) @confirm_namespace.route("/<string:confirmation_id>") class Confirmation(Resource): @classmethod def get(cls, confirmation_id: str): confirmation = ConfirmationModel.find_by_id(confirmation_id) if not confirmation: return {"message": "Confirmation not found"}, 404 if confirmation.expired: return {"message": "confirmation expired"}, 400 if confirmation.confirmed: return {"message": "already confirmed"}
from main import api, fields, Resource, db from models.usermodel import Users_model, user_schema, users_schema from flask_jwt_extended import ( JWTManager, jwt_required, create_access_token, get_jwt_identity, ) ns_users = api.namespace("users", description="all tasks regarding users") # this helps the user know how to input the data user_model = api.model( "User", { "fullname": fields.String( description="Fullname is required", required=True, min_length=2), "email": fields.String(description="Your email", required=True, min_length=2), "password": fields.String(description="Your password", required=True, min_length=2), }, ) @ns_users.route("") class User_list(Resource): @api.doc(security="apikey") @jwt_required
from sqlalchemy.exc import IntegrityError from auth.auth import requires_auth, requires_auth_with_same_user from main import api, logger from flask_restx import Resource, abort from flask import request from models.user import user_model, user_list_model, user_patch_model from database.user import User from database.progress import Progress user_ns = api.namespace('users', description='User operations') @user_ns.route('/') class UserList(Resource): @user_ns.marshal_list_with(user_list_model) @requires_auth('read:user') def get(self, payload): """Get a list of all users. This endpoint requires read:user permission""" logger.info(f"GET request to user list from {request.remote_addr}") users = User.query.all() response = {"users": users, "count": len(users)} return response @user_ns.marshal_with(user_model, code=201) @user_ns.expect(user_model) @requires_auth()
from main import api, Resource, fields from accessToken import token import requests #requests library import os import password #file containing the generated password import timeformat #file containing the function to generate timestamp in the following format YYYYMMDDHHmmss generated_password = password.the_decoded_password generated_timestamp = timeformat.the_formatted_time # create a namespace for the stk resource ns_stkpush = api.namespace('stkpush', description="MPESA STK PUSH") stk_payload = api.model('Stk', { "phone_number": fields.String, "amount": fields.String }) @ns_stkpush.route('') class Stkpush(Resource): @api.expect(stk_payload) def post(self): """Use this API endpoint to initiate online payment on behalf of a customer.""" # get the payload data = api.payload # format the phone number in the right order formated_number = '254{}'.format(data['phone_number'][1:])
from main import api, Resource, fields from accessToken import token import os import requests import json # create a namespace ns_c2b = api.namespace('c2b', description="MPESA c2b") # describe the payload expected sim_transaction = api.model( 'Sim', { "amount": fields.Integer, "msisdn": fields.String, "billRefNumber": fields.String }) # Use this API to register validation and confirmation URLs on M-Pesa @ns_c2b.route('/registerurl') class C2b(Resource): def post(self): """Use this API endpoint to register validation and confirmation URLs on M-Pesa""" access_token = token api_url = "https://sandbox.safaricom.co.ke/mpesa/c2b/v1/registerurl" headers = {"Authorization": "Bearer %s" % access_token} request = { "ShortCode": os.environ.get( "BusinessShortCode"