def test_absolute(self, app, mocker): app.add_url_rule('/<foo>', 'foobar', view_func=lambda x: x) field = fields.Url('foobar', absolute=True) obj = mocker.Mock(foo=42) with app.test_request_context('/'): assert 'http://localhost/42' == field.output('foo', obj)
def test_invalid_object(self, app): app.add_url_rule('/<foo>', 'foobar', view_func=lambda x: x) field = fields.Url('foobar') with app.test_request_context('/'): with pytest.raises(fields.MarshallingError): field.output('foo', None)
def test_absolute(self, app, mocker): app.add_url_rule("/<foo>", "foobar", view_func=lambda x: x) field = fields.Url("foobar", absolute=True) obj = mocker.Mock(foo=42) with app.test_request_context("/"): assert "http://localhost/42" == field.output("foo", obj)
class UsuarioDto: api = Namespace('usuarios', description='Operações com usuários') usuarioinsert = api.model( 'usuarioinsert', { 'login': fields.String(required=True), 'nome': fields.String(required=True), 'senha': fields.String(required=True), 'perfil_id': fields.Integer(required=True, description='id do perfil') }) usuariolist = api.model( 'usuariolist', { 'id': fields.Integer(readonly=True), 'login': fields.String(required=True), 'nome': fields.String(required=True), 'ativo': fields.Boolean(), 'uri': fields.Url('api.usuarios_usuario_id'), 'perfil_id': fields.Integer(description='id do perfil') }) usuarioupdate = api.model( 'usuarioupdate', { 'login': fields.String(required=False), 'nome': fields.String(required=False), 'senha': fields.String(required=False), 'perfil_id': fields.Integer(required=False, description='id do perfil'), 'ativo': fields.Boolean(required=False, description='inativa/ativa usuário'), })
def test_without_endpoint(self, app, mocker): app.add_url_rule("/<foo>", "foobar", view_func=lambda x: x) field = fields.Url() obj = mocker.Mock(foo=42) with app.test_request_context("/foo"): assert "/42" == field.output("foo", obj)
def test_without_endpoint_invalid_object(self, app): app.add_url_rule("/<foo>", "foobar", view_func=lambda x: x) field = fields.Url() with app.test_request_context("/foo"): with pytest.raises(fields.MarshallingError): field.output("foo", None)
def test_without_endpoint_absolute_scheme(self, app, mocker): app.add_url_rule('/<foo>', 'foobar', view_func=lambda x: x) field = fields.Url(absolute=True, scheme='https') obj = mocker.Mock(foo=42) with app.test_request_context('/foo', base_url='http://localhost'): assert 'https://localhost/42' == field.output('foo', obj)
def test_without_endpoint_absolute_scheme(self, app, mocker): app.add_url_rule("/<foo>", "foobar", view_func=lambda x: x) field = fields.Url(absolute=True, scheme="https") obj = mocker.Mock(foo=42) with app.test_request_context("/foo", base_url="http://localhost"): assert "https://localhost/42" == field.output("foo", obj)
def test_without_endpoint(self, app, mocker): app.add_url_rule('/<foo>', 'foobar', view_func=lambda x: x) field = fields.Url() obj = mocker.Mock(foo=42) with app.test_request_context('/foo'): assert '/42' == field.output('foo', obj)
def test_absolute_scheme(self, app, mocker): """Url.scheme should override current_request.scheme""" app.add_url_rule("/<foo>", "foobar", view_func=lambda x: x) field = fields.Url("foobar", absolute=True, scheme="https") obj = mocker.Mock(foo=42) with app.test_request_context("/", base_url="http://localhost"): assert "https://localhost/42" == field.output("foo", obj)
def test_absolute_scheme(self, app, mocker): '''Url.scheme should override current_request.scheme''' app.add_url_rule('/<foo>', 'foobar', view_func=lambda x: x) field = fields.Url('foobar', absolute=True, scheme='https') obj = mocker.Mock(foo=42) with app.test_request_context('/', base_url='http://localhost'): assert 'https://localhost/42' == field.output('foo', obj)
def test_with_blueprint_absolute_scheme(self, app, mocker): bp = Blueprint('foo', __name__, url_prefix='/foo') bp.add_url_rule('/<foo>', 'foobar', view_func=lambda x: x) app.register_blueprint(bp) field = fields.Url(absolute=True, scheme='https') obj = mocker.Mock(foo=42) with app.test_request_context('/foo/foo', base_url='http://localhost'): assert 'https://localhost/foo/42' == field.output('foo', obj)
def test_with_blueprint_invalid_object(self, app): bp = Blueprint("foo", __name__, url_prefix="/foo") bp.add_url_rule("/<foo>", "foobar", view_func=lambda x: x) app.register_blueprint(bp) field = fields.Url() with app.test_request_context("/foo/foo"): with pytest.raises(fields.MarshallingError): field.output("foo", None)
def test_with_blueprint(self, app, mocker): bp = Blueprint("foo", __name__, url_prefix="/foo") bp.add_url_rule("/<foo>", "foobar", view_func=lambda x: x) app.register_blueprint(bp) field = fields.Url() obj = mocker.Mock(foo=42) with app.test_request_context("/foo/foo"): assert "/foo/42" == field.output("foo", obj)
def test_with_blueprint_absolute_scheme(self, app, mocker): bp = Blueprint("foo", __name__, url_prefix="/foo") bp.add_url_rule("/<foo>", "foobar", view_func=lambda x: x) app.register_blueprint(bp) field = fields.Url(absolute=True, scheme="https") obj = mocker.Mock(foo=42) with app.test_request_context("/foo/foo", base_url="http://localhost"): assert "https://localhost/foo/42" == field.output("foo", obj)
def test_with_blueprint(self, app, mocker): bp = Blueprint('foo', __name__, url_prefix='/foo') bp.add_url_rule('/<foo>', 'foobar', view_func=lambda x: x) app.register_blueprint(bp) field = fields.Url() obj = mocker.Mock(foo=42) with app.test_request_context('/foo/foo'): assert '/foo/42' == field.output('foo', obj)
def init_models(cls, api: Api): cls.label = api.model( 'Label', dict( label_id=fields.String(readOnly=True), name=fields.String(readOnly=True), uri=fields.Url('labels_label'), )) cls.box = api.model( 'Box', dict(top=fields.Float(), left=fields.Float(), bottom=fields.Float(), right=fields.Float())) cls.label_assignment = api.model( 'LabelAssignment', dict( label=fields.Nested(cls.label), label_assignment_id=fields.String(readOnly=True), box=fields.Nested(cls.box, allow_null=True), confidence=fields.Float(), origin=fields.String(), uri=fields.Url('labels_assignment'), )) cls.image = api.model( 'Image', dict( image_id=fields.String(readOnly=True, description='Image ID'), file=fields.String(readOnly=True, description='Image file name'), label_assignments=fields.List(fields.Nested( cls.label_assignment), readOnly=True), url=fields.String(readOnly=True, description='Image file url'), thumbnail_url=fields.String(readOnly=True, description='Thumbnail file url'), uri=fields.Url('images_image'), ))
class PerfilDto: api = Namespace('perfis', description='Operações com Perfis de Usuario') perfil = api.model('perfil', { 'id' : fields.Integer(description = 'id do perfil'), 'nome': fields.String(required=True, description='nome do perfil'), 'uri' : fields.Url('api.perfis_perfil', readonly=True), 'ativo': fields.Boolean(description='ativo'), }) perfilinsert = api.model('perfilinsert', { 'nome': fields.String(required=True, description='nome do perfil'), }) perfilupdate = api.model('perfilupdate', { 'nome': fields.String(required=True, description='nome do perfil'), 'ativo': fields.Boolean(description='ativo'), })
def map_marshmallow_field_to_api_field(cls, marshmallow_field: mf.Field): if isinstance(marshmallow_field, mf.String): return frf.String() if isinstance(marshmallow_field, (mf.Raw, mf.Mapping, mf.Dict)): return frf.Raw() if isinstance(marshmallow_field, (mf.List, mf.Tuple)): return frf.List( cls.map_marshmallow_field_to_api_field( marshmallow_field.inner)) if isinstance(marshmallow_field, (mf.Number, mf.Integer, mf.Decimal, mf.Int)): return frf.Integer() if isinstance(marshmallow_field, (mf.Boolean, mf.Bool)): return frf.Boolean() if isinstance(marshmallow_field, mf.Float): return frf.Float() if isinstance(marshmallow_field, mf.Date): return frf.Date() if isinstance(marshmallow_field, mf.DateTime): return frf.DateTime() if isinstance(marshmallow_field, (mf.Url, mf.URL)): return frf.Url() raise Exception(f"Cannot map {marshmallow_field} to API model field")
@api.route('/json/<string:capture_uuid>/cookies') @api.doc(description='Get the complete cookie jar created during the capture.', params={'capture_uuid': 'The UUID of the capture'}) class CaptureCookies(Resource): def get(self, capture_uuid: str): return json.loads(lookyloo.get_cookies(capture_uuid).read()) # Just text submit_fields_post = api.model( 'SubmitFieldsPost', { 'url': fields.Url(description="The URL to capture", required=True), 'listing': fields.Integer(description="Display the capture on the index", min=0, max=1, example=1), 'user_agent': fields.String(description="User agent to use for the capture", example=''), 'referer': fields.String(description="Referer to pass to the capture", example=''), 'proxy': fields.Url( description= "Proxy to use for the capture. Format: [scheme]://[username]:[password]@[hostname]:[port]",
from sqlalchemy import text from flask_restx import Namespace, Resource, reqparse, fields, marshal from hotel_api.models import db, Hotels, RoomInventory availabilities_ns = Namespace("availabilities") hotel_fields = availabilities_ns.model( "availabilities", { "name": fields.String(example="1_Ceres"), "established_date": fields.String(example="1801-Jan-01"), "proprietor": fields.String(example="Piazzi, G."), "astrd_diameter": fields.Float(example="939.4"), "astrd_surface_composition": fields.String(example="carbonaceous"), "uri": fields.Url("api.hotel", example="/hotels/1"), }, ) # Parse search parameters from url query string reqparse = reqparse.RequestParser() reqparse.add_argument( "name", type=str, required=False, location="args", action="append" ) reqparse.add_argument( "checkin", type=lambda s: date.fromisoformat(s), required=True, location="args" ) reqparse.add_argument( "checkout", type=lambda s: date.fromisoformat(s), required=True, location="args" ) reqparse.add_argument(
'name': fields.String(required=True, example='SpamHaus eDROP'), 'organization': fields.String, 'list_type': fields.String(required=True, example='values'), 'tag_on_match': fields.Boolean(example=False), 'data_type_uuid': fields.String(required=True), 'values': fields.String(example='127.0.0.1\n4.4.4.4\n1.1.1.1'), 'polling_interval': fields.Integer(example=3600), 'url': fields.Url(description='A URL to pull threat data from', example='https://www.spamhaus.org/drop/edrop.txt'), 'to_memcached': fields.Boolean, 'active': fields.Boolean(example=True), 'csv_headers': fields.String, 'csv_headers_data_types': fields.String, 'case_sensitive': fields.Boolean }) mod_list_values = api.model('ListValues', {'values': fields.List(fields.String)})
def protected(*args): if "X-Requested-With" in request.headers: return fn(*args) else: return "X-Requested-With header missing", HTTPStatus.FORBIDDEN return protected a_user = api.model( "User", { "google_id": fields.Integer(description="The user's Google account ID"), "name": fields.String(description="The user's full name"), "picture": fields.Url(description="A URL to the profile image"), }, ) @api.route("/me") class Me(Resource): @login_required @csrf_protection @api.response(HTTPStatus.OK, "Success", a_user) def get(self): return { "google_id": current_user.id, "name": current_user.name, "picture": current_user.profile_pic, }
from flask import Flask, send_from_directory from flask_restx import Api, Resource, fields app = Flask(__name__) api = Api(app) @api.route('/hello') class HelloWorld(Resource): def get(self): return {'hello': 'world'} model = api.model('Model', { 'task': fields.String, 'uri': fields.Url('todo_ep') }) class TodoDao(object): def __init__(self, todo_id, task): self.todo_id = todo_id self.task = task # This field will not be sent in the response self.status = 'active' @api.route('/todo') class Todo(Resource): @api.marshal_with(model)
payload_artifact = ns.model( "Testing Farm results artifact", { "commit-sha": fields.String( required=True, example="08bfc38f15082bdf9ba964c3bbd04878666d1d56" ), "copr-chroot": fields.String(required=True, example="fedora-30-x86_64"), "copr-repo-name": fields.String( required=True, example="packit/packit-service-hello-world-14" ), "git-ref": fields.String( required=True, example="08bfc38f15082bdf9ba964c3bbd04878666d1d56" ), "git-url": fields.Url( required=True, example="https://github.com/packit/hello-world" ), "repo-name": fields.String(required=True, example="hello-world"), "repo-namespace": fields.String(required=True, example="packit-service"), }, ) payload_pipeline = ns.model( "Testing Farm results pipeline", { "id": fields.String( required=True, example="614d240a-1e27-4758-ad6a-ed3d34281924" ) }, ) payload = ns.model( "Testing Farm results",
def test_defaults(self): field = fields.Url('endpoint') assert not field.required assert field.__schema__ == {'type': 'string'}
required=True, description= "1 lowercase, 1 uppercase, 1 number, min 8 char, max 32 char", example="Password123", pattern=r'(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,32}$'), "displayName": fields.String( required=True, description="CooL-Name", example="chinchilla2", pattern= r'^[a-zA-Z0-9]+([a-zA-Z0-9](_|-| )[a-zA-Z0-9])*[a-zA-Z0-9]+$'), "avatar": fields.Url( # needs work for url required=False, default=None, description="Url for avatar", example="www.image.gif"), "level": fields.String(required=False, default="Beginner", description="level", example="Beginner"), "state": fields.String(required=False, default="OFFLINE", description="player state", example="IN_LOBBY, IN_GAME, OFFLINE", enum=['IN_LOBBY', 'IN_GAME', 'OFFLINE']), "activeGameId": fields.String(required=False, default=None, example="1"),
def test_defaults(self): field = fields.Url("endpoint") assert not field.required assert field.__schema__ == {"type": "string"}
requestPostParser.add_argument('password', type=str, location='json') reponseModel = api.model( 'ResponseModel', { 'Seq': fields.Integer, 'Id': fields.String, 'Password': fields.String, 'Salt': fields.String, 'Status': fields.String, 'AddTime': fields.String }) responseBody = api.model( 'ResponseBody', { 'uri': fields.Url(), 'code': fields.Integer, 'msg': fields.String, 'data': fields.List( fields.Nested(reponseModel)), # data 안에 json list 형식으로 설정 }) # 아래와 같이 하나의 클래스(url)에서 전송타입(get,post,delete ... ) 등으로 기능을 구분할 경우 각 타입에 맞는 기능 정의를 명확하게 하는것이 안전함 # get = 조회 , post = 데이터 insert , put = 데이터 update , delete = 데이터 삭제 @api.route('/auth/login') class Auth(Resource): @api.expect(requestPostParser) # request body parsing #cookie 저장을 위해 make_response사용하게 되면 model set 이 적용되지 않아 주석처리 #@api.marshal_with(responseBody) # response model set def post(self): # 수동 로그인
"access_token": fields.String, "token_type": fields.String(example="bearer"), "expires_in": fields.Integer(example=3600), }, ) auth_status = auth_ns.inherit( "auth_status", auth_user, { "token_expires_in": fields.Integer(example=3600), "is_admin": fields.Boolean(example="False"), "is_deactivated": fields.Boolean(example="False"), "created_date": fields.DateTime(example="2020-12-01T01:59:39.297904"), "last_modified_date": fields.DateTime(example="2020-12-01T01:59:39.297904"), "uri": fields.Url("api.user"), }, ) class AuthRegister(Resource): @auth_ns.expect(auth_password, validate=True) @marshal_with(auth_token) @auth_ns.response(400, "Validation error.") @auth_ns.response( 201, "Created.", auth_token, headers={"Cache-Control": "no-store", "Pragma": "no-cache"}, ) def post(self):