Commit 6386565f authored by Caleb Connolly's avatar Caleb Connolly

Figuring out how to do DI injection with flask_restful... No luck so far

parent 5cabd47b
from flask import request
from apikeys import apikeys
def authenticate(f):
def wrapper(*args, **kw):
if not 'key' in request.args:
return {
"message": "You must provide an API key"
key = request.args['key']
print("Key was:", apikeys[[k['key'] for k in apikeys].index(key)]['description'])
return f()
return wrapper
\ No newline at end of file
File added
import sqlite3
from models import *
# Database abstraction layer, simplifies db lookups
class HouseDbContext():
def __init__(self, dbfile):
self._file = dbfile
self.conn = None
self.cursor = None
def connect(self):
self.conn = sqlite3.connect(self._file)
self.cursor = self.conn.cursor()
def get_houses(self) -> list:
return [House(x) for x in self.cursor.execute("SELECT * FROM Houses").fetchall()]
def get_house(self, houseId: int):
return House(self.cursor.execute("SELECT * FROM Houses WHERE HouseId={}".format(houseId)).fetchall()[0])
def update_housepoints(self, house: House) -> bool:
self.cursor.execute("UPDATE Houses SET HousePoints=? WHERE HouseId=?", (house.housePoints, house.houseId))
\ No newline at end of file
class House():
def __init__(self, houseId: int, HouseName: str, HousePoints: int = 0):
self.houseId = houseId
self.houseId = HouseName
self.housePoints = HousePoints
def __init__(self, dbRow : tuple):
self.houseId = int(dbRow[0])
self.houseName = dbRow[1]
self.housePoints = int(dbRow[2])
def __eq__(self, shorthand):
if type(shorthand) is int:
return self.houseId == shorthand
if type(shorthand) is str and len(shorthand) == 1:
return self.houseName[0].lower() == shorthand.lower()
return self.houseName.lower() == shorthand.lower()
def __str__(self):
return "House ID: {}\nHouse Name: {}".format(self.houseId, self.houseId)
def serialize(self):
return self.__dict__
class User():
def __init__(self, userId: int, discordId: int, houseId: int, memberRolesId: int):
self.userId = userId
self.discordId = discordId
self.houseId = houseId
self.memberRolesId = memberRolesId
\ No newline at end of file
from flask_restful import Resource
from flask_restful import Resource, reqparse
from flask import request
from injector import Module
user_parser = reqparse.RequestParser()
user_parser.add_argument('username', help = 'This field cannot be blank', required = True)
user_parser.add_argument('password', help = 'This field cannot be blank', required = True)
class UserRegistration(Resource):
def post(self):
data = user_parser.parse_args()
return data
from database import HouseDbContext
from auth import authenticate
from models import *
class UserLogin(Resource):
def post(self):
return {'message': 'User login'}
class UserLogoutAccess(Resource):
# class DbContext(Module):
# @provider
# @singleton
# def provide_ext(self, app: Flask) -> HouseDbContext:
# return HouseDbContext("data/data.db")
class GivePoints(Resource):
method_decorators = [authenticate]
def post(self):
return {'message': 'User logout'}
class UserLogoutRefresh(Resource):
def post(self):
return {'message': 'User logout'}
class TokenRefresh(Resource):
def post(self):
return {'message': 'Token refresh'}
class AllUsers(Resource):
def get(self):
return {'message': 'List of users'}
if not 'user' in request.form:
return {
"message": "Must specify a user to receive points"
userid = request.form['user']
user = User.getUserByStuId(userid)
class GetPoints(Resource):
# def __init__(self, db: HouseDbContext):
# print("Called!!!!!!!!")
# self.db = db
def delete(self):
return {'message': 'Delete all users'}
class SecretResource(Resource):
def get(self):
if not ('user' in request.args or 'house' in request.args):
return {
"message": "Must specify a house or user to get points"
return {
'answer': 42
\ No newline at end of file
"message": "WIP"
from flask import Flask
from flask import Flask, request
from flask_restful import Api
from flask_injector import FlaskInjector
from database import HouseDbContext
app = Flask(__name__)
api = Api(app)
API_ROOT = "/api/v1"
import views, models, resources
import views, models, resources, database
api.add_resource(resources.GivePoints, f'{API_ROOT}/givePoints')
api.add_resource(resources.GetPoints, f'{API_ROOT}/getPoints')
def configure(binder):
# Initialize Flask-Injector. This needs to be run *after* you attached all
# views, handlers, context processors and template globals.
api.add_resource(resources.UserRegistration, f'{API_ROOT}/registration')
api.add_resource(resources.UserLogin, f'{API_ROOT}/login')
api.add_resource(resources.UserLogoutAccess, f'{API_ROOT}/logout/access')
api.add_resource(resources.UserLogoutRefresh, f'{API_ROOT}/logout/refresh')
api.add_resource(resources.TokenRefresh, f'{API_ROOT}/token/refresh')
api.add_resource(resources.AllUsers, f'{API_ROOT}/users')
api.add_resource(resources.SecretResource, f'{API_ROOT}/secret')
\ No newline at end of file
FlaskInjector(app=app, modules=[configure])
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment