def register_routes(app: Flask) -> None: # noqa api = Api(app) # noqa api.add_resource(Version, '/api/v1/') api.add_resource(IssueTokens, '/api/v1/token/issue') api.add_resource(RefreshTokens, '/api/v1/token/refresh') api.add_resource(UserCreate, '/api/v1/user/create') api.add_resource(CreateImage, '/api/v1/container/create')
def create_app(port=8000): """ Create Flask app object. :param port: TCP port for service to use. :type port: int :return: Flask app object :rtype: Flask() """ app = Flask(__name__) # we need to add redirect for '/' to '/setup' before # connecting api to app or else the rule for '/' inserted # by the api creation will override. app.add_url_rule('/', 'ROOT_REDIRECT', methods=['GET'], view_func=redirect_root) api = Api(app, doc='/apidoc/') driver = TelescopeModel() api.add_resource(AlpacaTelescope, '/api/v1/telescope/0/<string:action>', endpoint='Alpaca', resource_class_kwargs={'driver': driver}) api.add_resource(About, '/about', endpoint='About', resource_class_kwargs={'driver': driver}) api.add_resource(MonitorEncoders, '/encoders', endpoint='Encoders', resource_class_kwargs={'driver': driver}) api.add_resource(GlobalSetup, '/setup', endpoint='GlobalSetup', resource_class_kwargs={ 'driver': driver, 'server_ip': '127.0.0.1', 'server_port': port }) api.add_resource(DeviceSetup, '/setup/v1/telescope/0/setup', endpoint='DeviceSetup', resource_class_kwargs={'driver': driver}) return app
def test_no_crossdomain(self, app, client): class Foo(Resource): def get(self): return "data" api = Api(app) api.add_resource(Foo, "/test/") res = client.get("/test/") assert res.status_code == 200 assert "Access-Control-Allow-Origin" not in res.headers assert "Access-Control-Allow-Methods" not in res.headers assert "Access-Control-Max-Age" not in res.headers
def setUp(self): routes.FrontEndDbInterface = DbInterfaceMock app = Flask(__name__) app.config.from_object(__name__) app.config['TESTING'] = True config = get_config_for_testing() api = Api(app) endpoint, methods = routes.FSMetadataRoutesRest.ENDPOINTS[0] api.add_resource(routes.FSMetadataRoutesRest, endpoint, methods=methods, resource_class_kwargs={'config': config}) self.test_client = app.test_client()
def test_json_float_marshalled(self, app, client): api = Api(app) class FooResource(Resource): fields = {"foo": fields.Float} def get(self): return marshal({"foo": 3.0}, self.fields) api.add_resource(FooResource, "/api") resp = client.get("/api") assert resp.status_code == 200 assert resp.data.decode("utf-8") == '{"foo": 3.0}\n'
def test_access_control_expose_headers(self, app, client): class Foo(Resource): @cors.crossdomain( origin="*", expose_headers=["X-My-Header", "X-Another-Header"]) def get(self): return "data" api = Api(app) api.add_resource(Foo, "/test/") res = client.get("/test/") assert res.status_code == 200 assert "X-MY-HEADER" in res.headers["Access-Control-Expose-Headers"] assert "X-ANOTHER-HEADER" in res.headers[ "Access-Control-Expose-Headers"]
def test_access_control_expose_headers(self, app, client): class Foo(Resource): @cors.crossdomain( origin='*', expose_headers=['X-My-Header', 'X-Another-Header']) def get(self): return "data" api = Api(app) api.add_resource(Foo, '/test/') res = client.get('/test/') assert res.status_code == 200 assert 'X-MY-HEADER' in res.headers['Access-Control-Expose-Headers'] assert 'X-ANOTHER-HEADER' in res.headers[ 'Access-Control-Expose-Headers']
def test_crossdomain(self, app, client): class Foo(Resource): @cors.crossdomain(origin='*') def get(self): return "data" api = Api(app) api.add_resource(Foo, '/test/') res = client.get('/test/') assert res.status_code == 200 assert res.headers['Access-Control-Allow-Origin'] == '*' assert res.headers['Access-Control-Max-Age'] == '21600' assert 'HEAD' in res.headers['Access-Control-Allow-Methods'] assert 'OPTIONS' in res.headers['Access-Control-Allow-Methods'] assert 'GET' in res.headers['Access-Control-Allow-Methods']
def test_crossdomain(self, app, client): class Foo(Resource): @cors.crossdomain(origin="*") def get(self): return "data" api = Api(app) api.add_resource(Foo, "/test/") res = client.get("/test/") assert res.status_code == 200 assert res.headers["Access-Control-Allow-Origin"] == "*" assert res.headers["Access-Control-Max-Age"] == "21600" assert "HEAD" in res.headers["Access-Control-Allow-Methods"] assert "OPTIONS" in res.headers["Access-Control-Allow-Methods"] assert "GET" in res.headers["Access-Control-Allow-Methods"]
def init_app(app, api: Api): api.add_resource(ImageController, '/images/<string:idx>', endpoint='images') api.add_resource(ImagesUploadController, '/images', endpoint='image') api.add_resource(MetadataController, '/images/meta/<string:idx>', endpoint='meta') api.add_resource(ThumbnailController, '/images/thumbnail/<string:idx>', endpoint='thumbnail') if 'ENV' in app.config and app.config['ENV'] == 'development': data = api.as_postman(urlvars=False, swagger=True) print(' * Postman collection import:', json.dumps(data))
def test_will_prettyprint_json_in_debug_mode(self, app, client): api = Api(app) class Foo1(Resource): def get(self): return {"foo": "bar", "baz": "asdf"} api.add_resource(Foo1, "/foo", endpoint="bar") foo = client.get("/foo") # Python's dictionaries have random order (as of "new" Pythons, # anyway), so we can't verify the actual output here. We just # assert that they're properly prettyprinted. lines = foo.data.splitlines() lines = [line.decode() for line in lines] assert "{" == lines[0] assert lines[1].startswith(" ") assert lines[2].startswith(" ") assert "}" == lines[3] # Assert our trailing newline. assert foo.data.endswith(b"\n")
categoryDictTotal[category] = 0 categoryDict[category] = categoryDict[category] + correctCount categoryDictTotal[ category] = categoryDictTotal[category] + totalResponse resultDict[category] = (categoryDict[category] / categoryDictTotal[category]) * 100 for key in resultDict: temp = {} temp["x"] = key temp["y"] = resultDict[key] result.append(temp) return result class QuizAnalytics(Resource): def post(self): data = request.get_json() quiz_id = ObjectId(data.get('id')) q = quizCollection.find({"_id": quiz_id}) apiResult = {} questionResult = listQstns(q) q = quizCollection.find({"_id": quiz_id}) categoryResult = categoryAnlys(q) apiResult["questions"] = questionResult apiResult["categories"] = categoryResult print(apiResult) return jsonify(apiResult) api.add_resource(QuizAnalytics, '/analytics/getDataForViz')
from git_gateway.utils.cache import flask_cache app = Flask(__name__) api = Api(app) flask_cache.init_app(app) @api.errorhandler(Exception) def handle_internal_server_error(error): logging.error(error) return {'message': 'Internal Server Error'}, 500 @api.route('/liveness') class Liveness(Resource): def get(self): try: return {'status': 'OK'} except Exception as e: logging.error(e) return {'status': 'NOK'}, 500 api.add_resource(User, '/users/<string:username>/repos', endpoint='user_ep') api.add_resource(Repo, '/repos/<string:username>/<string:repo_name>', endpoint='repo_ep') if __name__ == '__main__': app.run(debug=True)
# src/__init__.py from flask import Flask from flask_restx import Api, Resource app = Flask(__name__) api = Api(app) app.config.from_object('src.config.DevelopmentConfig') class Ping(Resource): def get(self): return {'status': 'success', 'message': 'pong!'} # app.add_url_rule('/', Ping) api.add_resource(Ping, '/ping')
data = {} results = [] for q in quizCollection.find({}): quiz = {} data = q quiz_id = data["_id"] quiz_name = data["quiz_name"] publish = data["published_date"] question_list = data["questions"] mark = 0 for question in question_list: mark += question["marks"] response_list = question["responses"] q_totalmark = 0 for response in response_list: print(response["eval"]) if response["eval"] == "Correct": q_totalmark += question["marks"] #avg #print(quiz_name,publish,concepts,mark,avg_que_score) quiz["quiz_name"] = quiz_name quiz["publish"] = publish # quiz["class"] = classroom_name quiz["marks"] = str(mark) results.append(quiz) print(results) return jsonify(results) api.add_resource(Certificate, '/getcertificate')
client = pymongo.MongoClient( "mongodb+srv://shwethasubash:[email protected]/QuizzRoom?retryWrites=true&w=majority" ) db = client.QuizzRoom userCollection = db.Question_temp class QuestionDetails(Resource): def get(self): results = userCollection.aggregate([{ '$match': { 'questionId': { '$gte': 1 } } }]) questionSet = [] for result in results: question = {} question['questionId'] = result['questionId'] question['question'] = result['question'] question['options'] = result['options'] question['selectedOption'] = False question['type'] = result['type'] questionSet.append(question) return {"QuestionSet": questionSet} api.add_resource(QuestionDetails, '/fetchQuestions')
# project/api/ping.py from flask import Blueprint from flask_restx import Api, Resource ping_blueprint = Blueprint("ping", __name__) api = Api(ping_blueprint) class Ping(Resource): def get(self): return {"status": "success", "message": "pong"} api.add_resource(Ping, "/ping")
}, ) @api.expect(parser) @jwt_required def get(self): try: query = request.args.get("q") user_id = request.args.get("uid") msg_id = request.args.get("mid") bot_id = request.args.get("bid") if query: # Obtém a resposta de acordo com a query informada return get_answer(query, msg_id, user_id, bot_id), 200 else: response_json = { "msg": "Parameter is missing in the query string.", } return response_json, 400 except Exception as e: response_json = {"msg": e} return response_json, 500 # Definir as rotas de acesso api.add_resource(UserRegisterAPI, "/register") api.add_resource(UserLoginAPI, "/login") api.add_resource(LogoutAPIAccess, "/logout/access") api.add_resource(LogoutAPIRefresh, "/logout/refresh") api.add_resource(TokenRefreshAPI, "/refresh") api.add_resource(QASucupira, "/search")
def handle_httpx_request_error(error): return { 'message': 'An error occurred while requesting the given URL.', 'url': error.request.url, 'details': '\n'.join(error.args) } @api.route('/website') class Website(Resource): @api.marshal_with(website_response_model) @api.expect(website_request_parser, validate=True) @api.response(500, description='The request to the given URL failed', model=httpx_request_error_model) def get(self): """ Get the HTML of the given website. """ args = website_request_parser.parse_args() url = args['url'] response = httpx.get(url) return WebsiteResponseData(url=url, content=response.text) api.add_resource(Website, '/website') if __name__ == '__main__': app.run()
post_data = request.get_json() username = post_data.get("username") email = post_data.get("email") response_object = {} user = User.query.filter_by(email=email).first() if user: response_object["message"] = "Sorry. That email already exists." return response_object, 400 db.session.add(User(username=username, email=email)) db.session.commit() response_object["message"] = f"{email} was added!" return response_object, 201 @api.marshal_with(user, as_list=True) def get(self): return User.query.all(), 200 class Users(Resource): @api.marshal_with(user) def get(self, user_id): user = User.query.filter_by(id=user_id).first() if not user: api.abort(404, f"User {user_id} does not exist") return user, 200 api.add_resource(UsersList, "/users") api.add_resource(Users, "/users/<int:user_id>")
from .app import app from flask_restx import Api from inventory.resources import InventoryResource # start API api = Api(app, prefix="/") api.add_resource(InventoryResource, "/inventory", "/inventory/<inventory_code>")
except Exception as e: print(e); def delete(self,name): Student.delete_data(name); return {"Status":"Record Removed"},200 def post(self,name): try: data = request.get_json(); id_list = (data['id']) name_list = data['name']; my_tup = list(zip(id_list,name_list)) print(my_tup) z = Student.insert_data(my_tup); return {"Status":"Data_Inserted","data":z},201 except Exception as e: print(e); api.add_resource(Details,'/student/<string:name>') app.run(debug=True);
invited_user = Invited_user.query.filter_by( email=email, invite_code=invite_code).first() if invited_user: user = User(name, email, password, invited_user.role_id) db.session.add(user) db.session.commit() response_object['message'] = f'{email} was added!' return response_object, 201 else: print(invited_user.role_id) response_object['message'] = 'Not authorised' return response_object, 401 api.add_resource(SignUp, '/users') class AllUsers(Resource): @api.marshal_with(user) def get(self): users = User.query.all() return users api.add_resource(AllUsers, '/allusers') class Users(Resource): @api.marshal_with(user) def get(self, user_id):
faq_blueprint = Blueprint('faq', __name__) api = Api(faq_blueprint) client = pymongo.MongoClient( "mongodb+srv://shwethasubash:[email protected]/<dbname>?retryWrites=true&w=majority" ) db = client.QuizzRoom faqs = db.FAQ class FAQs(Resource): def get(self): data = {} results = [] #iterate through all FAQs present in the mongoDB collection for question in faqs.find({}): lst = {} ques = question["question"] #fetch questions ans = question[ "answer"] #fetch answers to the corresponding question lst["question"] = ques lst["answer"] = ans results.append(lst) return jsonify(results) #return all FAQs in json data format api.add_resource(FAQs, '/faq')
def get(self, name): item = self.get_item(name) return {'item': item}, 200 if item else 404 def get_item(self, name): item = next(filter(lambda x: x['name'] == name, items), None) return item def post(self, name): if self.get_item(name): return { 'message': 'An item with name {} already exists'.format(name) }, 422 data = request.get_json() item = {'name': name, 'price': data['price']} items.append(item) return {'item': item}, 201 class ItemList(Resource): @jwt_required() def get(self): return {'items': items} api.add_resource(Item, '/item/<string:name>') api.add_resource(ItemList, '/items') app.run(debug=True)
except ValidationError: return response_object, 401 class Users(Resource): # get a user by id def get(self, user_id): response_object = { 'status': 'fail', 'message': 'User does not exist', } try: user = User.query.filter_by(id=user_id).first() if not user: return response_object, 404 else: response_object = {'status': 'success', 'data': user.to_json()} return response_object, 200 except (ValueError, DataError): return response_object, 404 api.add_resource(Ping, '/api/users/ping') api.add_resource(UsersList, '/api/users') api.add_resource(Users, '/api/users/<user_id>')
app = Flask(__name__) app.json_encoder = CustomJSONEncoder app.config['JWT_SECRET_KEY'] = 'jwt-secret-key' app.config['JSON_SORT_KEYS'] = False db = MongoEngine(app) jwt = JWTManager(app) api = Api(app) class BackendError(Exception): pass # abort(400, custom='Oop! Something went wrong!!!') @api.route('/<string:pan_number>') class Sample(Resource): # data = parser.parse_args() def get(self, pan_number): testdate = date(1990,10,25) access_token = create_access_token(identity = pan_number) return jsonify({ 'pan': pan_number, 'name': 'Dinesh Kumar', 'dob': testdate, 'father_name': 'Hari Kumar', 'client_id': access_token }) api.add_resource(Sample, '/<string:pan_number>', endpoint='pan_number_ep') if __name__ == '__main__': app.run(debug=True)
# create tables @app.before_first_request def create_tables(): db.create_all() jwt = JWTManager(app) # This method will check if a token is blacklisted, and will be called automatically when blacklist is enabled @jwt.token_in_blacklist_loader def check_if_token_in_blacklist(decrypted_token): return ( decrypted_token["jti"] in BLACKLIST ) # Here we blacklist particular JWTs that have been created in the past. api.add_resource(UserRegister, "/register") api.add_resource(UserLogin, "/login") api.add_resource(User, "/user/<int:user_id>") api.add_resource(Item, "/item/<int:id>") api.add_resource(Items, "/item") api.add_resource(Store, "/store/<int:id>") api.add_resource(Stores, "/store") api.add_resource(UserLogout, "/logout") api.add_resource(TokenRefresh, "/refresh") if __name__ == "__main__": app.run()
if not user: api.abort(404, f"User {user_id} does not exist") return user, 200 class UsersList(Resource): @api.marshal_with(user, as_list=True) def get(self): return User.query.all(), 200 @api.expect(user, validate=True) def post(self): post_data = request.get_json() username = post_data.get('username') email = post_data.get('email') response_object = {} user = User.query.filter_by(email=email).first() if user: response_object['message'] = 'Sorry. That email already exists.' return response_object, 400 db.session.add(User(username=username, email=email)) db.session.commit() response_object['message'] = f'{email} was added!' return response_object, 201 api.add_resource(UsersList, '/users') api.add_resource(Users, '/users/<int:user_id>')
# if not is_admin(resp.id): # response_object['message'] = \ # "You do not have permission to do that." # return response_object, HTTPStatus.UNAUTHORIZED if not file_contents or not file_name or not file_extension: return response_object, HTTPStatus.BAD_REQUEST try: a_byte_array = bytearray(file_contents, "utf8") new_file = FileModel(name=file_name, extension=file_extension, data=a_byte_array) db.session.add(new_file) db.session.commit() response_object = { 'status': 'success', 'message': 'file was added.' } return response_object, HTTPStatus.CREATED except Exception as e: log.error(e) files_api.add_resource(Files, '/app/v1/files/<token>') files_api.add_resource(FilesList, '/app/v1/files')