def setUp( self ): app = Flask( __name__ ) root = os.path.join( os.path.dirname( __file__ ), "schemas" ) JSONSchemaValidator( app=app, root=root ) app.config[ 'TESTING' ] = True client = app.test_client() self.app = app self.client = client
def create_app(): app = Flask(__name__) # Middleware app.wsgi_app = Middleware(app.wsgi_app, prefix='/api/v1') # add CORS support CORS(app) # Authentication app.config['JWT_SECRET_KEY'] = os.getenv('SECRET_KEY') # Database app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv( 'SQLALCHEMY_DATABASE_URI') app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = os.getenv( 'SQLALCHEMY_TRACK_MODIFICATIONS') # Request Validator JSONSchemaValidator(app=app, root="schemas/validations") return app
from flask import Flask, jsonify, abort, request, Response from flask_restful import HTTPException from flask_migrate import Migrate from flask_jsonschema_validator import JSONSchemaValidator from flask_cors import CORS from sqlalchemy.orm import load_only from sqlalchemy.sql import text from .models import db, Task, Hint, HintStatus, Image, User from .config import SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, DISCORD_WEBHOOK, \ SECRET_JWT_KEY, SECURITY_PASSWORD_SALT from . import tasks_helpers, hints_helpers, images_helpers, users_helpers app = Flask(__name__) JSONSchemaValidator(app=app, root="schemas") app.config["SQLALCHEMY_DATABASE_URI"] = SQLALCHEMY_DATABASE_URI app.config["SQLALCHEMY_MIGRATE_REPO"] = SQLALCHEMY_MIGRATE_REPO app.config['SECRET_JWT_KEY'] = SECRET_JWT_KEY app.config['SECURITY_PASSWORD_SALT'] = SECURITY_PASSWORD_SALT cloudinary.config(cloud_name="du95usvl0", api_key="738462148762527", api_secret="t9Jri_atBqGG7yJkmqHmTmKY_V4") db.init_app(app) migrate = Migrate(app, db) CORS(app, resources={ r"/api/*": {
import jsonschema from flask import Response from flask import Flask, request from flask_jsonschema_validator import JSONSchemaValidator from controller.createAccount import accountCreate from controller.transactionAuthorization import makeTrasact app = Flask(__name__) JSONSchemaValidator(app=app, root="requests") @app.route("/account", methods=["POST"]) @app.validate('createAccount', 'createrequest') def crea(): a = accountCreate(request.json) return a @app.route("/transaction", methods=["POST"]) @app.validate('makeTransaction', 'transactionrequest') def trans(): b = makeTrasact(request.json) return b @app.errorhandler(jsonschema.ValidationError) def onValidationError(e): return Response("There was a validation error: " + str(e), 422) #app.run(debug=True)
# -*- coding: future_fstrings -*- import os from flask_jsonschema_validator import JSONSchemaValidator class AppWrapper(object): def __init__(self): self.extensions = {} json_schema_validator = JSONSchemaValidator(app=AppWrapper(), root=f"{os.path.dirname(os.path.realpath(__file__))}")
import asyncio import jsonschema from flask import Blueprint, request, Response from flask_jsonschema_validator import JSONSchemaValidator from src.ultimateam.application.controllers.api.ExchangeController import ExchangeController exchange = Blueprint('exchange', __name__) JSONSchemaValidator(app=exchange, root="schemas") @exchange.route('/handshake', methods=['POST']) @exchange.validate('exchange', 'fut_info') def handshake(): # request for permission to exchange # if we are happy we give you a token to trade else we say bye ctrl = ExchangeController(request) return ctrl.handshake() @exchange.route('/exchange', methods=['POST']) def exchange(): # initiate the exchange, i.e start distribution of the requested resources ctrl = ExchangeController(request) run([ctrl.performExchange()]) return Response('Working on the exchange') @exchange.route('/rays', methods=['POST']) def delete():
def create_app(test_config=None): # create and configure the app app = Flask(__name__) setup_db(app) CORS(app) JSONSchemaValidator(app=app, root="schemas") @app.after_request def after_request(response): response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization') response.headers.add('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS') return response @app.route('/categories') def get_categories(): '''Get all categories''' categories = Category.query.order_by(Category.id.asc()).all() return jsonify({'categories': {c.id: c.type for c in categories}}) @app.route('/questions') def get_questions(): '''Get questions paginated''' page = request.args.get('page', 1, type=int) (start, stop, per_page) = paginate(page) questions = Question.query.order_by(Question.id.asc()).slice( start, stop).all() total_questions = Question.query.count() categories = Category.query.all() return jsonify({ 'questions': [q.format() for q in questions], 'total_questions': total_questions, 'per_page': per_page, 'page': page, 'categories': {c.id: c.type for c in categories}, 'current_category': None }) @app.route('/questions', methods=['POST']) @app.validate('question', 'create') def add_question(): '''Create question''' data = request.get_json(force=True) fields = ('question', 'answer', 'category', 'difficulty') question = Question(**{k: data[k] for k in fields if k in data}) db.session.add(question) db.session.commit() return jsonify(question.format()) @app.route('/questions/<int:question_id>', methods=['DELETE']) def delete_question(question_id): '''Delete a question by it's ID''' question = Question.query.get(question_id) if question is None: return abort(404) db.session.delete(question) db.session.commit() return jsonify({'success': True, 'id': question.id}) @app.route('/questions/searches', methods=['POST']) def search_questions(): '''Search Questions''' data = request.get_json(force=True) search = data.get('searchTerm') filters = [Question.question.ilike("%{}%".format(search))] categ_id = data.get('categoryId') if categ_id: filters = [Question.category == categ_id] + filters questions = Question.query.order_by( Question.id.asc()).filter(*filters).all() return jsonify({ 'questions': [q.format() for q in questions], }) @app.route('/category/<int:category_id>/questions') def get_category_questions(category_id): '''Get paginated questions of specified category''' page = request.args.get('page', 1, type=int) (start, stop, per_page) = paginate(page) categ = Category.query.get(category_id) if categ is None: return abort(404) questions = Question.query.order_by(Question.id.asc()).filter( Question.category == category_id).slice(start, stop).all() total_questions = Question.query.filter( Question.category == category_id).count() return jsonify({ 'questions': [q.format() for q in questions], 'total_questions': total_questions, 'per_page': per_page, 'page': page, 'current_category': category_id }) @app.route('/quizzes', methods=['POST']) def get_quiz_question(): '''Get a question for the quiz''' data = request.get_json(force=True) filters = [Question.id.notin_(data.get('previousQuestions'))] categ_id = data.get('quizCategory') if categ_id: filters = [Question.category == categ_id] + filters questions = Question.query.filter(*filters).all() question = None if len(questions) > 0: question = random.choice(questions) return jsonify({ 'question': None if question is None else question.format(), }) @app.errorhandler(jsonschema.ValidationError) def onValidationError(e): return jsonify({'error': "There was a validation error: " + str(e)}), 400 @app.errorhandler(404) def not_found(error): return jsonify({'error': 'Not Found'}), 404 @app.errorhandler(422) def bad_request(error): return jsonify({'error': 'Bad request or data'}), 422 return app
@celery.task(bind=True, queue='unified') def add(self, x, y, z, q): cmd = [x, y, z] meta = {'cmd': x, 'argy': y, 'argz': z, 'extid': q} p = Popen(cmd, stdout=PIPE, stderr=PIPE) self.update_state(state='RUNNING', meta={'cmd': cmd, 'argy': y, 'argz': z, 'extid': q}) time.sleep(30) stdout, stderr = p.communicate() output = {'stderr': stderr, 'stdout': stdout} return (meta, output) app = Flask(__name__) JSONSchemaValidator(app=app, root='./') @app.route('/task', methods=['PUT']) @app.validate('schema', 'register') def long_task(): ext_id = request.headers.get('X-Correlation-ID') data = request.get_json() retval = redis_extid_exist(ext_id) if retval: guid = redis_get_guid(ext_id) state = {'conflict': {'ext_id': ext_id, 'guid': guid}} return jsonify(state), 409 x = data['argx'] y = data['argy'] z = data['argz']