def create_app(test_config=None): # create and configure the app app = Flask(__name__) app.config.from_object('config') setup_db(app) CORS(app, resource={r'/api/*': {'origins': '*'}}) @app.after_request def after_request(response): response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization,true') response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS') return response categories_controller(app) questions_controller(app, int(app.config['QUESTIONS_PER_PAGE'])) quizzes_controller(app) @app.errorhandler(404) def not_found(error): return jsonify({ "success": False, "error": 404, "message": "resource not found" }), 404 @app.errorhandler(422) def unprocessable(error): return jsonify({ "success": False, "error": 422, "message": "unprocessable" }), 422 return app
def create_app(): app = Flask(__name__) database.setup_db(app) CORS(app) """ TODO-DONE: uncomment the following line to initialize the database !! NOTE THIS WILL DROP ALL RECORDS AND START YOUR DB FROM SCRATCH !! NOTE THIS MUST BE UNCOMMENTED ON FIRST RUN """ # database.db_drop_and_create_all() """ ROUTES """ """ TODO-DONE: implement endpoint GET /drinks it should be a public endpoint it should contain only the drink.short() data representation returns status code 200 and json {"success": True, "drinks": drinks} where drinks is the list of drinks or appropriate status code indicating reason for failure """ @app.route("/drinks") def drinks(): if drinks := Drink.all(): return jsonify({"success": True, "drinks": drinks}) else:
def add_task_result(task_result): ''' This will be called from a client and executed on the master ''' logger.debug("Got task_result result -> adding to DB") try: # This will be called from the celery worker and not from the main module, therefore we need to make sure, that the DB is initialized database.setup_db() with database.get_session() as session: # T inst = session.query(Task).filter(Task.task_id == task_result.task_id) result = inst.one() result.completed = task_result.completed result.output = task_result.output result.build_logs = ''.join(task_result.build_logs) result.exception = task_result.exception result.traceback = task_result.traceback result.worker_hostname = task_result.hostname result.exit_code = task_result.exit_code result.duration = task_result.duration session.commit() except: logger.error(traceback.format_exc()) return False return True
def setUp(self): """Define test variables and initialize app.""" # binds the app to the current context self.app = create_app() setup_db(self.app) self.client = self.app.test_client self.headers = { "Authorization": "bearer " + os.environ["VALID_TEST_TOKEN"] } Monster( name="monster_name", race="monster_race", health_points="100", armor_points="100", attack_damage="100", xp_drop="100", ).insert() Dungeon( level="1", rooms="1", treasures="1", traps="1", boss_level=False, xp_drop="1000", ).insert()
def setUp(self): """Define test variables and initialize app.""" self.app = create_app() self.client = self.app.test_client self.database_path = database["path"] self.database_path = self.database_path.replace("postgres://","postgresql://") setup_db(self.app, self.database_path) # binds the app to the current context with self.app.app_context(): self.db = SQLAlchemy() self.db.init_app(self.app) # create all tables self.db.create_all() # set tokens self.simpletoken = bearer_tokens["inspector"] self.admintoken = bearer_tokens["admin"] #Initialize try: #Clear the database self.client().get("/deleteall",headers={'Authorization': f"Bearer {self.admintoken}"}) #add initial data self.client().get("/bulk",headers={'Authorization': f"Bearer {self.admintoken}"}) except: print("The test script could not be initialised.") #Test data self.new_question = { "question": "Does the movie have a lot of romance?", "category_id":1, "Type":"Generic" } self.new_movie = { "title": "Casino Royale", "category_id":1, "description":"After receiving a license to kill, British Secret Service agent James Bond (Daniel Craig) heads to Madagascar, where he uncovers a link to Le Chiffre (Mads Mikkelsen), a man who finances terrorist organizations. Learning that Le Chiffre plans to raise money in a high-stakes poker game, MI6 sends Bond to play against him, gambling that their newest operative will topple the man's organization." } self.new_category = { "category": "Some new category" } self.new_answer = { "answer":0.5 }
def create_app(test_config=None): app = Flask(__name__) app.config["JSON_SORT_KEYS"] = False setup_db(app) CORS(app) @app.route("/") def get_greeting(): return "Welcome to Dungeon Monsters API - For usage, please refer to docs" """ ### Routes: Dungeons """ @app.route("/dungeons", methods=["GET"]) @requires_auth("get:dungeons") def get_dungeons(): if dungeons := Dungeon.all(): result = {"success": True, "Dungeons": dungeons} return jsonify(result) else:
def start_master(): logger.debug("Launching master daemon") database.setup_db() database.create_schema() if config.insert_inital_data: database.insert_initial_data() # Start celery worker to consume results fn = get_user_demote() if fn is None: process = Popen([ "celery", "worker", "--app=celerycontrol", "-l", "info", "-Q", "results" ]) else: process = Popen([ "celery", "worker", "--app=celerycontrol", "-l", "info", "-Q", "results" ], preexec_fn=fn) master_api.setup.run()
# -*- coding: utf-8 -*- from bson.json_util import dumps from bson.regex import Regex from flask import Flask, request from database import setup_db from helper import get_scraped_date app = Flask(__name__) collection = setup_db() @app.route('/bbc') def bbc_articles(): # TODO consider adding more query parameters title = request.args.get('title', '') tag = request.args.get('tag', '') scraped_date = get_scraped_date(request) items = collection.find({ "$and": [{ 'title': Regex(title) }, { 'tag': Regex(tag) }, { 'scraped_date': scraped_date }] }) return dumps(items)
import ConnMan import Blackjack_Server import matchmaking_Server import database if __name__ == "__main__": database.setup_db() print("Database Initialised") ConnMan.start() print("Conn Man initialised") matchmaking_Server.start() print("Matchmaking Initialised")
def setUp(self): self.app = app.test_client() self.collection = setup_db()
def create_app(test_config=None): """ ######################################################### Init FLASK ######################################################### """ app = Flask(__name__) setup_db(app) CORS(app) ITEMS_PER_PAGE = pagination["example"] """ ######################################################### CORS Headers ######################################################### """ @app.after_request def after_request(response): response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization,true') response.headers.add('Access-Control-Allow-Methods', 'GET,POST,DELETE,PATCH') return response """ ######################################################### ENDPOINTS ######################################################### """ @app.route("/login-results", methods=["GET"]) def hello(): return (jsonify({ "success": True, "message": "You have been logged in. Save the access_token from the URL above." })) @app.route("/logout", methods=["GET"]) def bye(): return (jsonify({ "success": True, "message": "You have been logged out." })) @app.route('/', methods=["GET"]) def play(): category_id = 1 cat = Category.query.get(category_id) if cat == None: abort(404) # Get frontend data question_id = request.args.get('question', None) answer = request.args.get('answer', None) # Load model model = pickle.load( open(f"models/latest_model_{category_id}.pkl", "rb")) if answer == None: # Initial question: Save a new session on start now = datetime.now() sess = Session(timestamp=now, category_id=category_id, num_questions=0) sess.insert() session_id = sess.id # Return random question responses_so_far = [] session_finder = finder(model, use_model="advanced", responses_so_far=responses_so_far) # Start with a random question next_q_id = np.random.choice( list(session_finder.feature_imp.keys())) # Get initial question q = Question.query.get(int(next_q_id)) return render_template('index.html', question=next_q_id, question_text=q.question, session=session_id) # Run within the game #Get session_id from URL and load data try: session_id = int(request.args.get('session', None)) except: abort(422) sess = Session.query.get(int(session_id)) # Get responses_so_far responses = Quiz.query.filter(Quiz.session_id == session_id).all() responses_so_far = [{ e.question_id: float(e.answer) } for e in responses] # Launch finder session_finder = finder(model, use_model="advanced", responses_so_far=responses_so_far) # Count questions num_questions = len(responses) + 1 # Update question count in session database sess.num_questions = num_questions sess.update() # Add current answer session_finder._add_answer(int(question_id), float(answer)) # Predict result = session_finder._predict() #Save answer to db and best predict probability try: new = Quiz(question_id=int(question_id), answer=float(answer), session_id=session_id, category_id=category_id, num_question=num_questions, predict_proba=result["best_item_prob"]) new.insert() except: abort(422) # Stop if there is no more questions to ask or threshold has been reached if len(session_finder.available_questions ) == 0 or result["best_item_prob"] > 0.28: best_idx = result['best_item_id'] m = Movie.query.get(int(best_idx)) return render_template('index.html', result=m.title, session=session_id) next_q_id = int(result["next_question_id"]) next_question_text = result["next_question_text"] return render_template('index.html', question=next_q_id, question_text=next_question_text, session=session_id, prob=result["best_item_prob"]) ############# Questions #################### @app.route('/questions/categories/<category_id>', methods=["GET"]) @requires_auth(permission='get:questionbycategory') def get_question_category(payload, category_id): data = Question.query.filter(Question.category_id == category_id).all() selection = paginate(request, data, ITEMS_PER_PAGE) if len(selection) == 0: abort(404) return (jsonify({"success": True, "data": selection})) @app.route('/questions/<question_id>', methods=["GET"]) @requires_auth(permission='get:singlequestion') def get_question(payload, question_id): q = Question.query.get(int(question_id)) if q == None: abort(404) return (jsonify({ "success": True, "id": q.id, "question": q.question, "Type": q.Type, "category": q.category.format() })) @app.route('/questions', methods=["POST"]) @requires_auth(permission='post:question') def add_question(payload): body = request.get_json() try: question = body.get("question", None) category_id = body.get("category_id", None) Type = body.get("Type", None) if exist(Question, question, "question"): abort(422) else: new_q = Question(question=question, category_id=category_id, Type=Type) new_q.insert() except: abort(422) return (jsonify({ "success": True, "added_question_id": new_q.id, "added_question": new_q.question, "Type": new_q.Type, "category": new_q.category.format() })) ############# Movies #################### @app.route('/movies/categories/<category_id>', methods=["GET"]) @requires_auth(permission='get:moviebycategory') def get_movie_category(payload, category_id): data = Movie.query.filter(Movie.category_id == category_id).all() selection = paginate(request, data, ITEMS_PER_PAGE) if len(selection) == 0: abort(404) return (jsonify({"success": True, "data": selection})) @app.route('/movies/<movie_id>', methods=["GET"]) @requires_auth(permission='get:singlemovie') def get_movie(payload, movie_id): movie = Movie.query.get(int(movie_id)) if movie == None: abort(404) return (jsonify({ "success": True, "id": movie.id, "title": movie.title, "description": movie.description, "category": movie.category.format() })) @app.route('/movies/<movie_id>', methods=["PATCH"]) @requires_auth(permission='patch:movie') def update_movie(payload, movie_id): body = request.get_json() try: req_title = body.get("title") movie = Movie.query.filter(Movie.id == movie_id).one_or_none() movie.title = req_title movie.update() except: abort(404) return (jsonify({"success": True, "movies": movie.format()})) @app.route('/movies', methods=["POST"]) @requires_auth(permission='post:movie') def add_movie(payload): body = request.get_json() try: title = body.get("title", None) description = body.get("description", None) category_id = body.get("category_id", None) if exist(Movie, title, "title"): abort(422) else: new = Movie(title=title, description=description, category_id=category_id) new.insert() except: abort(422) return (jsonify({ "success": True, "added_movie_id": new.id, "added_movie": new.title, "category": new.category.format() })) ############# Category #################### @app.route('/categories', methods=["GET"]) def retrieve_categories(): data = Category.query.order_by("id").all() selection = paginate(request, data, ITEMS_PER_PAGE) if len(selection) == 0: abort(404) return (jsonify({"success": True, "data": selection})) @app.route('/categories', methods=["POST"]) @requires_auth(permission='post:category') def add_category(payload): body = request.get_json() try: category = body.get("category", None) if exist(Category, category, "category"): abort(422) else: new = Category(category=category) new.insert() except: abort(422) return (jsonify({ "success": True, "added_category_id": new.id, "added_category": new.category })) ############# Question Movie Answers #################### @app.route('/movieData/categories/<category_id>', methods=["GET"]) @requires_auth(permission='get:answersbycategory') def get_answer_category(payload, category_id): data = QuestionMovie.query.filter( QuestionMovie.movie.has(category_id=category_id)).all() selection = paginate(request, data, ITEMS_PER_PAGE) if len(selection) == 0: abort(404) return (simplejson.dumps({"success": True, "data": selection})) @app.route('/movieData/<movie_id>/question/<question_id>', methods=["GET"]) @requires_auth(permission='get:singleanswer') def get_answer(payload, movie_id, question_id): #try: selection = QuestionMovie.query.filter( and_(QuestionMovie.question_id == int(question_id), QuestionMovie.movie_id == int(movie_id))).one_or_none() if selection == None: abort(404) else: return (jsonify({"success": True, "data": selection.format()})) #except: # abort(404) @app.route('/movieData/<movie_id>/question/<question_id>', methods=["DELETE"]) @requires_auth(permission='delete:answer') def delete_answer(payload, movie_id, question_id): selection = QuestionMovie.query.filter( and_(QuestionMovie.question_id == question_id, QuestionMovie.movie_id == movie_id)).one_or_none() if selection == None: abort(404) else: selection.delete() return (jsonify({ "success": True, "deleted_answer": selection.format() })) @app.route('/movieData/<movie_id>/question/<question_id>', methods=["POST"]) @requires_auth(permission='post:answer') def add_answer(payload, movie_id, question_id): body = request.get_json() #Check if ids have been passed correctly and the resources exist movie = Movie.query.get(int(movie_id)) question = Question.query.get(int(question_id)) if (movie == None) or (question == None): abort(404) #Check if for this combination a data entry already exists selection = QuestionMovie.query.filter( and_(QuestionMovie.question_id == question_id, QuestionMovie.movie_id == movie_id)).one_or_none() if selection != None: abort(422) #Add new data try: answer = float(body.get("answer", None)) new = QuestionMovie(question_id=question_id, movie_id=movie_id, answer=answer) new.insert() except: abort(422) return (simplejson.dumps({ "success": True, "added_answer_id": new.id, "added_answer": new.answer, "movie": movie.title, "question": question.question })) ############# Other #################### @app.route("/deleteall", methods=["GET"]) @requires_auth(permission='get:deleteall') def delete_all(payload): db_drop_and_create_all() return (jsonify({ "success": True, "message": "all data has been erased from the databases" })) @app.route('/bulk', methods=["GET"]) @requires_auth(permission='get:bulk') def bulk_add_example_data(payload): categories = pd.read_csv("initialdata/categories.csv", sep=";") movies = pd.read_csv("initialdata/movies.csv", sep=";") questions = pd.read_csv("initialdata/questions.csv", sep=";") movie_answers = pd.read_csv("initialdata/question_movie_mapping.csv", sep=";", decimal=",") #Add example categories for i, row in categories.iterrows(): new = Category(category=row["Category"]) new.insert() #Add example movies for i, row in movies.iterrows(): new = Movie(title=row["title"], description=row["description"], category_id=row["category_id"]) new.insert() #Add example questions for i, row in questions.iterrows(): new = Question(question=row["question"], category_id=row["category_id"], Type=row["Type"]) new.insert() #Add Question Answers for i, row in movie_answers.iterrows(): for question_id in movie_answers.columns[1:]: new = QuestionMovie(question_id=question_id, movie_id=row["movie_id"], answer=row[question_id]) new.insert() return (jsonify({"success": True})) """ ######################################################### ERROR HANDLING ######################################################### """ @app.errorhandler(406) def missing_param(error): return jsonify({ "success": False, "error": 406, "message": "Missing parameters" }), 406 @app.errorhandler(422) def unprocessable(error): return jsonify({ "success": False, "error": 422, "message": "unprocessable" }), 422 @app.errorhandler(404) def not_found(error): return (jsonify({ "success": False, "error": 404, "message": "Resource not found" }), 404) @app.errorhandler(400) def bad_request(error): return (jsonify({ "success": False, "error": 400, "message": "Bad request" }), 400) @app.errorhandler(500) def server_error(error): return (jsonify({ "success": False, "error": 500, "message": "Internal server error" }), 500) @app.errorhandler(AuthError) def auth_error(error): return (jsonify({ "success": False, "error": error.status_code, "message": error.error['message'] }), error.status_code) return app
def create_app(test=False): app = Flask(__name__) setup_db(app, test) CORS(app, resources={r"/*": {"origins": "*"}}) @app.route("/") def index(): return {"success": True, "message": "API is live and running"} @app.after_request def after_request_func(response): response.headers.add("Access-Control-Allow-Origin", "*") return response #### # Error Handlers #### @app.errorhandler(400) def bad_request(error): return (jsonify({ "success": False, "error": 400, "message": "bad request" }), 400) @app.errorhandler(404) def not_found(error): return ( jsonify({ "success": False, "error": 404, "message": "resource not found" }), 404, ) @app.errorhandler(422) def unprocessable(error): return ( jsonify({ "success": False, "error": 422, "message": "unprocessable" }), 422, ) @app.errorhandler(500) def internal_error(error): return ( jsonify({ "success": False, "error": 500, "message": "internal server failure" }), 500, ) return app
def create_app(): app = Flask(__name__) app.config.from_object('config') database.setup_db(app) errorFlag = 0 @app.after_request def after_request(response): response.headers.add('Access-Control-Allow-Methods', 'GET,POST') return response def get_unit_name(): unitName = input("enter unit name...\t") return " ".join(unitName.split()) # move all extra spaces in the name ################################################# # check if the given unit name is empty as just press enter def check_empty_unit_name(unitName): if (len(unitName) == 0): # could be if(unitName is '\r') too return True else: return False ############################################## # ask database to search about given unit name data def ask_database(unitName): try: unitData = Unit.query.filter(Unit.name.ilike(unitName)).one_or_none() return unitData # if can not retrive any data from db or enen None, then there is an error except (Exception, psycopg2.DatabaseError) as error: global errorFlag print(error) errorFlag = 1 return error # abort(500) ######################################### # ask api to search about given unit name data def ask_api(unitName): apiUrl = "https://age-of-empires-2-api.herokuapp.com/api/v1/unit/"+unitName # gey datas for a specific unit from api request = requests.get(apiUrl) if 'json' in request.headers.get('Content-Type'): data = request.json() else: return False # data = json.loads(request.content) return data #################################### # is the given unit is in api or not founded def is_exist_in_api(data): # mesage is a dictionary key,returned if the api doesn't have given unit if "message" in data: print('not in the api') # input not found abort(404) else: return True ############################### # is this unit had gained attack bouns def has_attack_bonus(new_unit_attack_bonuses): if (new_unit_attack_bonuses is None): return False else: return True ############################ # is this unit had gained armor bouns def has_armor_bonus(new_unit_armor_bonuses): if (new_unit_armor_bonuses is None): return False else: return True ######################### # save new unit data into postgres database # unit attributes which Could have None value are not mandatory to have value def set_new_unit_data_into_db(data): new_unit_id = data["id"] new_unit_name = data['name'] new_nuit_description = data['description'] if "description" in data else None new_unit_expansion = data['expansion'] new_unit_age = data['age'] new_unit_created_in = data['created_in'] new_unit_cost = data['cost'] # ubit 43 reload_time constrain(not null) so I but any number to pass new_unit_build_time = data['build_time'] if "build_time" in data else 1 # ubit 53 reload_time constrain not null, so I but any number to pass new_unit_reload_time = data['reload_time'] if "reload_time" in data else 1.2 new_unit_attack_delay = data['attack_delay'] if "attack_delay" in data else None new_unit_movement_rate = data['movement_rate'] new_unit_line_of_sight = data['line_of_sight'] new_unit_hit_points = data['hit_points'] new_unit_range = data['range'] if "range" in data else None # ubit 53 attack constrain not null, so I but any number here to pass test new_unit_armor = data['armor'] new_unit_attack = data['attack'] if "attack" in data else 1 new_unit_armor = data['armor'] new_unit_search_radius = data['search_radius'] if "search_radius" in data else None new_unit_accuracy = data['accuracy'] if "accuracy" in data else None new_unit_blast_radius = data['blast_radius'] if "blast_radius" in data else None new_unit_attack_bonuses = data['attack_bonus'].copy() if "attack_bonus" in data else None new_unit_armor_bonuses = data['armor_bonus'].copy() if "armor_bonus" in data else None # see if the unit has attack/armor bounses attack_bonus = has_attack_bonus(new_unit_attack_bonuses) armor_bonus = has_armor_bonus(new_unit_armor_bonuses) try: # save unit data into unit table new_unit = Unit(id=new_unit_id, name=new_unit_name, description=new_nuit_description, expansion=new_unit_expansion, age=new_unit_age, created_in=new_unit_created_in, cost=new_unit_cost, build_time=new_unit_build_time, reload_time=new_unit_reload_time, attack_delay=new_unit_attack_delay, movement_rate=new_unit_movement_rate, line_of_sight=new_unit_line_of_sight, hit_points=new_unit_hit_points, unit_range=new_unit_range, attack=new_unit_attack, armor=new_unit_armor, search_radius=new_unit_search_radius, accuracy=new_unit_accuracy, blast_radius=new_unit_blast_radius) new_unit.insert() # in case unit has poth attack and armor bouns if ((attack_bonus is True) and (armor_bonus is True)): new_attack_bouns = AttackBouns(attackBouns=new_unit_attack_bonuses) new_armor_bouns = ArmorBouns(armorBouns=new_unit_armor_bonuses) new_unit.attack_bonuses = [new_attack_bouns] new_unit.armor_bonuses = [new_armor_bouns] new_attack_bouns.insert() new_armor_bouns.insert() # in case unit has only armor bouns elif((attack_bonus is False) and (armor_bonus is True)): new_armor_bouns = ArmorBouns(armorBouns=new_unit_armor_bonuses) new_unit.armor_bonuses = [new_armor_bouns] new_armor_bouns.insert() # in case unit has only attack bouns elif((attack_bonus is True) and (armor_bonus is False)): new_attack_bouns = AttackBouns(attackBouns=new_unit_attack_bonuses) new_unit.attack_bonuses = [new_attack_bouns] new_attack_bouns.insert() except (Exception, psycopg2.DatabaseError) as error: print('error during saving into database') print(error) return error finally: db.session.close() ####################################### def retrive_unit_data_from_db(unitData): # dectionary to read data coming from db in it all_data = {} # start setting data into dectionary all_data["id"] = unitData.id all_data["name"] = unitData.name # (check it to print only data which have values) if (unitData.description is not None): all_data["description"] = unitData.description all_data["expansion"] = unitData.expansion all_data["age"] = unitData.age all_data["created_in"] = unitData.created_in all_data["cost"] = unitData.cost all_data["build_time"] = unitData.build_time # convert decimal object data to float then to json object all_data["reload_time"] = json.dumps(float(unitData.reload_time)) if (unitData.attack_delay is not None): all_data["attack_delay"] = json.dumps(float(unitData.attack_delay)) all_data["movement_rate"] = json.dumps(float(unitData.movement_rate)) all_data["line_of_sight"] = unitData.line_of_sight all_data["hit_points"] = unitData.hit_points if (unitData.unit_range is not None): all_data["range"] = unitData.unit_range all_data["attack"] = unitData.attack all_data["armor"] = unitData.armor if (len(unitData.attack_bonuses) > 0): all_data["attack_bouns"] = [attack.attackBouns for attack in unitData.attack_bonuses] if (len(unitData.armor_bonuses) > 0): all_data["armor_bouns"] = [armor.armorBouns for armor in unitData.armor_bonuses] if (unitData.search_radius is not None): all_data["search_radius"] = unitData.search_radius if (unitData.accuracy is not None): all_data["accuracy"] = unitData.accuracy if (unitData.blast_radius is not None): all_data["blast_radius"] = unitData.blast_radius return all_data ################ # @app.route('/unit/<string:unit_name>', methods=['GET','POST']) @app.route('/', methods=['GET', 'POST']) def get_unit_data(): # read name from user on cmd or termnal unitName = get_unit_name() # see if the user just leave name empty nameFlag = check_empty_unit_name(unitName) # if name left empty if (nameFlag is True): print("error, empty input") # unprocessable abort(422) else: # search about data in db unitData = ask_database(unitName) if (errorFlag == 1): print('can not get from database', unitData) # return unitData elif unitData is not None: all_data = retrive_unit_data_from_db(unitData) print(json.dumps(all_data, indent=2)) # if unit data is not in database then search about it in the api elif unitData is None: # ask api about given unit name data data = ask_api(unitName) # if api not working if data is False: print("api is not working, we can not get data...") # if the api do really have given unit data or not apiFlag = is_exist_in_api(data) # if the given name is currently existed in the api # then return the nuit data from the api and save them into local database if apiFlag: set_new_unit_data_into_db(data) print(json.dumps(data, indent=2)) return with app.app_context(): get_unit_data() @app.errorhandler(400) def bad_request(error): return jsonify({ "success": False, "error": 400, "message": "bad request" }), 400 @app.errorhandler(404) def not_found(error): return jsonify({ "success": False, "error": 404, "message": "resource not found" }), 404 @app.errorhandler(500) def internal_server_error(error): return jsonify({ "success": False, "error": 500, "message": "internal server error" }), 500 return app
global maximum maximum = max return {"msg": f'Max have been changed to {max}'} @app.get('/api/get_max') def get_max(): global maximum return maximum @app.get('/api/get_current') def get_max(): global current return current @app.delete('/api/delete_user') def delete(id: int): return delete_user(id) @app.get('/') def test(): return {"test": {"id": 123}} if __name__ == "__main__": setup_db() uvicorn.run(app, host='0.0.0.0', port=8000)
cli.restart, filters=~Filters.update.edited_message) dispatch.add_handler(restart_handler) text_handler = MessageHandler( Filters.text & ~Filters.update.edited_message, cli.text) dispatch.add_handler(text_handler) dispatch.add_handler(CallbackQueryHandler(button_handler)) if __name__ == '__main__': logging.basicConfig(format=('%(asctime)s - %(name)s - ' '%(levelname)s - %(message)s'), level=logging.INFO) with open(".apikey", 'r') as f: API_KEY = f.read().strip() db.setup_db() updater = Updater(token=API_KEY, use_context=True) dispatcher = updater.dispatcher setup_handlers(dispatcher, updater.job_queue) ut.restore_trackings(updater.bot) updater.start_polling() updater.idle() ut.backup_trackings()
) existing_vote = session.query(Vote).filter(Vote.shader_id == shader_id, Vote.ip == ip) if existing_vote.count(): session.close() return bottle.abort(403, 'Forbidden') try: session.add(voting) session.commit() session.close() except: return bottle.abort(500, 'Internal Server Error') return json.dumps({'error': 'success'}) setup_db() class StripPathMiddleware(object): ''' Get that slash out of the request ''' def __init__(self, a): self.a = a def __call__(self, e, h): e['PATH_INFO'] = e['PATH_INFO'].rstrip('/') return self.a(e, h) if __name__ == '__main__': bottle.run(app=StripPathMiddleware(app), host='localhost', port=8080, debug=True)