Saravanan666/pypi-org huggingface dataset:
Package: api-service
Description of the Encryption ModuleThis module provides essential functionalities for secure authentication and password management in Python applications, particularly useful in web services developed with FastAPI. It is designed with a focus on security, efficiency, and ease of use.FeaturesJWT Token Managementcreate_jwt_token(payload: dict): Creates a JWT (JSON Web Token) with a custom payload, typically including user details like ID and role. The token is encrypted using a secret key and an algorithm specified in the environment variables. It has a default expiration of 7 days.check_token(token: str): Validates the given JWT token, verifying its integrity and authenticity. ReturnsTrueif the token is valid, otherwiseFalse.read_token_from_header(request: Request): Extracts and validates a JWT token from the HTTP request header. If the token is invalid or expired, it raises anHTTPExceptionwith appropriate status codes.read_token(token: str): Validates a given string token. Raises anHTTPExceptionif the token is invalid or expired, otherwise, returns the token's payload.Password Encryption and Verificationencrypt_password(password: str): Encrypts a plain password using bcrypt, providing a secure way to store passwords.check_password(plain_password: str, hashed_password: str): Verifies a plain password against its hashed version, typically used during the login process.This module is particularly suitable for web applications requiring robust authentication mechanisms and secure password handling.Description of the Query ModuleThis module is designed to handle and validate query strings in Python applications, especially in the context of web APIs developed using FastAPI and Pydantic. It focuses on flexibility and reliability in processing and validating query strings.FeaturesQuery String Decodingdecode_query(query: str): Decodes a query string into a dictionary. It can handle both URL-encoded JSON strings and standard query strings. For JSON strings, it parses them into a dictionary, and for standard query strings, it processes them as key-value pairs.Query Validationdecode_and_validate_query(query: str, validation_model: BaseModel): Decodes the given query string and then validates it against a specified Pydantic model. It ensures that the query matches the expected schema and data types.validate_query_over_schema(validation_model: BaseModel, query: dict): Validates a dictionary (typically the result of a decoded query) against a Pydantic model. It checks if all fields in the query are contained in the model and match the expected types. If the query is incorrect, it raises anHTTPExceptionwith details of the discrepancy.
Package: api-session
api-sessionapi-sessionis a small module providing an extendedrequests.Sessionclass to work with JSON APIs.We use it atBixotoas a basis for JSON API clients such asPyMagentoorPyBigBuy.It aims at factoring the common parts of these clients while staying very lightweight (<100 SLOC).Featuresbase URL: the base API URL is given only once on object creation; subsequent calls use.get("/path")read-only flag: if given, prevents the API from doingPOSTand similar callsoffline flag: if given, prevents the API from doing any call. This is useful for tests.requests.Sessioninheritance: the class inherits fromrequests.Session, so it stays 100% compatible with itInstallpip install api-sessionOr with Poetry:poetry add api-sessionDependency: Python 3.8+.Usagefromapi_sessionimportAPISessionclient=APISession("https://httpbin.org")client.get_json_api("/get")# => {...}
Package: api-shop
api-shopOnline Documents在线文档api-shop：一个易用的、快速的restful-api接口工具包，兼容：django/flask/bottle。一切只为少加班。demo 图片核心功能：配置化api生成。自动校验request提交的数据，并转换成指定格式，支持：int，float，list，dict，set，tuple，bool自动生成api文档，并提供一个web页面可供查询和mock数据演示。兼容django,flask,bottle(如果不指定框架，默认按这个顺序识别框架)自动生成接口骨架文件功能（请谨慎开启）。自定义格式转换器，data_format.datetime格式转换类；'2019-01-18 23:25:25' to datetime支持正则格式校验。多国语言支持，也支持自定义语言包。文档热重载。默认值支持方法函数。支持url中包含参数，例如/api/user/<id>，并且在配置methods参数的时候设置它的规则。支持多url绑定一个接口支持指定参数的可选项，例如：[1,4,7]，收到这个列表之外的参数就会触发bad_request可以在代码中直接调用Api业务代码：api_run（将移除get_api_result_json和get_api_result_response）支持在Api类中定义response_docs来制作返回值文档，并支持模型字段引入；以及模型部分字段引入类：ApiResponseModelFieldsOnline Documents在线文档
Package: apispec-clear-unusable
apispec-clear-unusablePlugin for apispec which helps reusing the documentation on a muti-endpoint function/method.Example with flask-restfulfromapispecimportAPISpecfromflaskimportFlask,jsonifyfromflask_restfulimportResource,ApifrommarshmallowimportSchema,fields# Create an APISpecspec=APISpec(title='Random swagger Petstore',version='1.0.0',plugins=['apispec.ext.flask','apispec.ext.marshmallow','brunoais.apispec.ext.clear_unusable',],)# This example uses flask but it also works with other frameworksapp=Flask(__name__)api=Api(app)classRandomPet(Resource):defget(self,species=None,race=None):"""A cute random furry animal.---description: Get a random petparameters:- in: pathname: speciestype: stringdescription: The species of the animal to be randomly selectedparameters:- in: pathname: racetype: stringdescription: The race of the animal to be randomly selectedresponses:200:description: A pet to be returnedschema: PetSchema"""returnget_random_pet(species=species,race=race),200api.add_resource(RandomPet,'/pets/random',endpoint='randompet')api.add_resource(RandomPet,'/pets/<species>/random',endpoint='randompet_species')api.add_resource(RandomPet,'/pets/<species>/races/<race>/random',endpoint='randompet_species_race')spec.definition('Category',schema=CategorySchema)spec.definition('Pet',schema=PetSchema)withapp.test_request_context():spec.add_path(view=random_pet)Output becomesdefinitions:
	#...
parameters: {}
paths:
  /pets/random:
    get:
      description: Get a random pet
      parameters: []
      responses:
        200:
          description: A pet to be returned
          schema: {$ref: '#/definitions/Pet'}
  /pets/{species}/random:
    get:
      description: Get a random pet
      parameters:
      - {description: The species of the animal to be randomly selected, in: path,
        name: species, required: true, type: string}
      responses:
        200:
          description: A pet to be returned
          schema: {$ref: '#/definitions/Pet'}
  /pets/{species}/races/{race}/random:
    get:
      description: Get a random pet
      parameters:
      - {description: The species of the animal to be randomly selected, in: path,
        name: species, required: true, type: string}
      - {description: The race of the animal to be randomly selected, in: path, name: race,
        required: true, type: string}
      responses:
        200:
          description: A pet to be returned
          schema: {$ref: '#/definitions/Pet'}
swagger: '2.0'Installationpip install apispec-clear-unusableLicenseThis is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Package: apispec-plugins
APISpecplugins for easy
integration with different components (web frameworks, packages, etc).FeaturesSupport for the OpenAPI Specification (versions 2 and 3)Support for frameworks/plugins which include:apispec_plugins.webframeworks.flaskapispec_plugins.ext.pydanticInstallationInstall the package directly fromPyPI(recommended):$pipinstallapispec-pluginsPlugin dependencies likeflaskandpydanticare not installed with the package by default. To
haveflaskandpydanticinstalled, run:$pipinstallapispec-plugins[flask,pydantic]Example UsagefromtypingimportOptionalfromapispecimportAPISpecfromapispec_plugins.base.mixinimportRegistryMixinfromapispec_plugins.ext.pydanticimportPydanticPluginfromapispec_plugins.webframeworks.flaskimportFlaskPluginfromflaskimportFlaskfrompydanticimportBaseModel# set APISpec pluginsspec=APISpec(title="Pet Store",version="1.0.0",openapi_version="3.0.3",info=dict(description="A minimal pet store API"),plugins=(FlaskPlugin(),PydanticPlugin()),)# optional Flask supportapp=Flask(__name__)# optional pydantic supportclassPet(BaseModel,RegistryMixin):id:Optional[int]name:str@app.route("/pet/<petId>")defpet(petId):"""Find pet by ID.
    ---
    get:
        parameters:
            - in: path
              name: petId
        responses:
             200:
                 description: display pet data
                 content:
                     application/json:
                         schema: Pet
    """returnf"Display pet with ID{petId}"# register `path` for the Flask routewithapp.test_request_context():spec.path(view=pet)Alternatively, toFlaskroutes,MethodViewcan be used:fromflask.viewsimportMethodViewclassPetAPI(MethodView):defget(self,petId):# get pet by IDpassapp.add_url_rule("/pet/<petId>",view_func=PetAPI.as_view("pet_view"))Dynamic specsAs seen so far, specs are specified in the docstring of the view or
class. However, with thespec_fromdecorator, one can dynamically
set specs:fromapispec_pluginsimportspec_from@spec_from({"parameters":{"in":"path","name":"petId"},"responses":{200:{"description":"display pet data"}},})defpet(petID):"""Find pet by ID."""passWhy notapispec-webframeworks?The conceiving of this project was based onapispec-webframeworks. While that project is focused on integrating web frameworks withAPISpec, this
project goes a step further in providing the best integration possible with theAPISpecstandards. Some
limitations on that project were also addressed, like:a path cannot register no more than 1 single rule per endpoint;limited docstring spec processing;Tests & linting 🚥Run tests withtox:# ensure tox is installed$toxRun linter only:$tox-elintOptionally, run coverage as well with:$tox-ecoverageLicenseMIT licensed. SeeLICENSE.
Package: apispec-py35-compat
A simple package that provides a deprecatedapispec.compatpackage for Python 3.5.
This package was removed fromapispecduring migration from Python 3.5.
It was required howeverapispec-webframeworks0.4.0 - the last version supporting Python 3.5.Be careful while uninstalling this package - it will dropapispecpackage as well.Fileapispec/compat.pyis copied from marshmallow-code package filesrc/marshmallow/compat.py
Package: apispec-starlette
Plugin for APISpec handling StarletteThis module should not be considered as stable as it is still under development.However a stable version can be expected by mid March 2020 and any issue or pull request is welcome at any time.Provides aplugin to use with APISpecto be able to handleStarletteendpoints.StarlettePlugin usagefromstarlette.applicationsimportStarlettefromapispecimportAPISpecfromapispec_starletteimportStarlettePluginapp=Starlette()spec=APISpec(title="My API",version="0.0.1",openapi_version="2.0",plugins=[StarlettePlugin(app)],)Documenting responses inside endpoint docstringfromstarlette.applicationsimportStarlettefromstarlette.responsesimportJSONResponsefromapispecimportAPISpecfromapispec_starletteimportStarlettePluginapp=Starlette()spec=APISpec(title="My API",version="0.0.1",openapi_version="2.0",plugins=[StarlettePlugin(app)],)@app.route("/my_endpoint")defmy_endpoint():"""responses:200:description: "Action performed"schema:properties:status:type: stringtype: object"""returnJSONResponse({"status":"test"})Documenting responses outside of endpoint docstringfromstarlette.applicationsimportStarlettefromstarlette.responsesimportJSONResponsefromapispecimportAPISpecfromapispec_starletteimportStarlettePlugin,document_responseapp=Starlette()spec=APISpec(title="My API",version="0.0.1",openapi_version="2.0",plugins=[StarlettePlugin(app)],)@app.route("/my_endpoint")defmy_endpoint():returnJSONResponse({"status":"test"})document_response(spec,endpoint="/my_endpoint",method="get",status_code=200,response={"description":"Action performed","schema":{"properties":{"status":{"type":"string"}},"type":"object",}})Documenting OAuth2 security outside of endpoint docstringfromstarlette.applicationsimportStarlettefromstarlette.middlewareimportMiddlewarefromstarlette.middleware.authenticationimportAuthenticationMiddlewarefromstarlette.authenticationimportrequires,AuthenticationBackendfromstarlette.responsesimportJSONResponsefromapispecimportAPISpecfromapispec_starletteimportStarlettePlugin,document_endpoint_oauth2_authentication,document_oauth2_authentication# TODO Replace by your OAuth2 backendapp=Starlette(middleware=[Middleware(AuthenticationMiddleware,backend=AuthenticationBackend())])spec=APISpec(title="My API",version="0.0.1",openapi_version="2.0",plugins=[StarlettePlugin(app)],)# TODO Adjust parametersdocument_oauth2_authentication(spec,authorization_url="http://authorization_url",flow="implicit",scopes={"scope1":"Description of scope 1","scope2":"Description of scope 2"})@requires(scopes=["scope1","scope2"])@app.route("/my_endpoint")defmy_endpoint():returnJSONResponse({"status":"test"})document_endpoint_oauth2_authentication(spec,endpoint="/my_endpoint",method="get",required_scopes=["scope1","scope2"])Add a /swagger.json endpointYour endpoints can be automatically discovered and documented when requesting /swagger.jsonfromstarlette.applicationsimportStarlettefromapispec_starletteimportadd_swagger_json_endpointapp=Starlette()spec=add_swagger_json_endpoint(app=app)How to installpython 3.6+must be installedUse pip to install module:python-mpipinstallapispec_starlette
Package: apispec-ui
A library to generate a UI interface from anAPISpecspecification. As per the APISpec initiative, it
currently supportsOpenAPI Specification(aka. Swagger specification) andSwaggerUI.FeaturesSupport for the OpenAPI Specification (versions 2 and 3)Compatibility with SwaggerUI (latest version - 4.18.1)Support for frameworks which include:FlaskInstallationInstall the package directly fromPyPI(recommended):$pipinstall-Uapispec-uiPlugin dependencies likeapispecandFlaskare not installed with the package by default. To
haveapispecandFlaskinstalled, run:$pipinstall-Uapispec-ui[apispec,flask]Example usageA simple example on how to work with aFlaskapplication:fromapispecimportAPISpecfromapispec.ext.marshmallowimportMarshmallowPluginfromapispec_pluginsimportFlaskPluginfromapispec_ui.flaskimportSwaggerfromflaskimportFlaskapp=Flask(__name__)apispec=APISpec(title="Pet Store",version="1.0.0",openapi_version="3.1.0",plugins=(FlaskPlugin(),MarshmallowPlugin()),# optional)...Swagger(app=app,apispec=apispec,config={})With this example, the application contains 2 extra views:swagger.ui: endpoint to serveSwaggerUIswagger.specs: endpoint to serveswaggerspecs, inyamlWithconfigsparameter one can tweak some parameters:config={"swaggerui":True,# enable/disable SwaggerUI"swagger_route":"/api/",# change swagger routes"swagger_static":"/static/",# change location for static files"swagger_favicon":"favicon.ico",# change favicon"swagger_hide_bar":True,# hide SwaggerUI top bar}These settings can also be configured through theSWAGGERconfig variable that is
part of the app config.In terms of precedence, the config that takes the most precedence is theconfigparameter fromSwaggerclass, followed by theSWAGGERapp config.Tests & linting 🚥Run tests withtox:# ensure tox is installed$toxRun linter only:$tox-elintOptionally, run coverage as well with:$tox-ecoverageLicenseMIT licensed. SeeLICENSE.
Package: apispec-webframeworks
apispecplugins for
integrating with various web frameworks.These plugins used to be inapispec.extbut have since
been moved to their own package.Included plugins:apispec_webframeworks.bottleapispec_webframeworks.flaskapispec_webframeworks.tornadoMigration fromapispec<1.0.0To migrate from older versions of apispec, install this package
withpip install apispec-webframeworksChange your imports, like so:# apispec<1.0.0fromapispec.ext.flaskimportFlaskPlugin# apispec>=1.0.0fromapispec_webframeworks.flaskimportFlaskPluginExample UsagefromflaskimportFlaskfromapispecimportAPISpecfromapispec.ext.marshmallowimportMarshmallowPluginfromapispec_webframeworks.flaskimportFlaskPluginfrommarshmallowimportSchema,fieldsspec=APISpec(title="Gisty",version="1.0.0",info=dict(description="A minimal gist API"),plugins=[FlaskPlugin(),MarshmallowPlugin()],)app=Flask(__name__)classGistParameter(Schema):gist_id=fields.Int()classGistSchema(Schema):id=fields.Int()content=fields.Str()@app.route("/gists/<gist_id>")defgist_detail(gist_id):"""Gist detail view.
    ---
    get:
        parameters:
                - in: path
                schema: GistParameter
        responses:
                200:
                schema: GistSchema
    """return"details about gist{}".format(gist_id)# Since `path` inspects the view and its route,# we need to be in a Flask request contextwithapp.test_request_context():spec.path(view=gist_detail)DocumentationFor documentation for a specific plugin, see its module docstring.DevelopmentClone and cd into this repoCreate and activate a virtual environmentInstall this package (in editable mode) and the development
dependencies$ pip install '.[dev]'Install pre-commit hooks$ pre-commit installRunning testsTo run all tests:$ pytestTo run syntax checks:$ tox -e lint(Optional) To run tests in all supported Python versions in their own virtual environments (must have each interpreter installed):$ toxLicenseMIT licensed. See the bundledLICENSEfile for more details.
Package: apisports
A simple python library for easy querying of APISports data.Example usagefromapisportsimportFootballapi=Football(api_key='XXXXXXXX')# get all players for Chelsea FC (id=49) for the 2020 season# and sort by ageplayers=api.players(season=2020,team=49)ifnotplayers.ok:print("something went wrong: "+players.error_description)else:sorted_by_age=sorted(players,key=lambdaplayer:player['player']['age'])defformat_player(player):return"{firstname}{lastname}:{age}".format(firstname=player['player']['firstname'],lastname=player['player']['lastname'],age=player['player']['age'])forplayerinsorted_by_age:print(format_player(player))outputs:Harvey Vale: 18
Dynel Simeu: 19
Myles Peart-Harris: 19
Ian Maatsen: 19
Valentino Livramento: 19
Lewis Bate: 19
Karlo Žiger: 20
Henry Lawrence: 20
Billy Gilmour: 20
Faustino Anjorin: 20
Armando Broja: 20
Marc Guehi: 21
Conor Gallagher: 21
Tariq Lamptey: 21
Juan Familia-Castillo: 21
Ethan Ampadu: 21
Callum Hudson-Odoi: 21
Jamie Cumming: 22
Luke McCormick: 22
Kai Havertz: 22
Mason Mount: 22
Reece James: 22
Christian Pulisic: 23
Nathan Baxter: 23
Isaiah Brown: 24
Fikayo Tomori: 24
Jake Clarke-Salter: 24
Tammy Bakumo-Abraham: 24
Ruben Loftus-Cheek: 25
Robert Kenedy Nunes do Nascimento: 25
Ben Chilwell: 25
Timo Werner: 25
Andreas Bødtker Christensen: 25
Lewis Baker: 26
Kepa Arrizabalaga Revuelta: 27
Emerson Palmieri dos Santos: 27
Mateo Kovačić: 27
Kurt Happy Zouma: 27
Ross Barkley: 28
Hakim Ziyech: 28
Antonio Rüdiger: 28
Michy Batshuayi Tunga: 28
Davide Zappacosta: 29
Edouard Mendy: 29
Jorge Luiz Frello Filho: 30
N'Golo Kanté: 30
Victor Moses: 31
Marcos Alonso Mendoza: 31
César Azpilicueta Tanco: 32
Willian Borges da Silva: 33
Pedro Eliezer Rodríguez Ledesma: 34
Olivier Giroud: 35
Thiago Emiliano da Silva: 37
Wilfredo Daniel Caballero: 40
Package: api-sports-io-nfl
api-sports-io-nflAn unofficial Python API wrapper forapi-sports.io's NFL feeds.Installationpipinstallapi-sports-io-nflUsagefromapi_sports_io_nflimportApiNfl# Initialize the API wrapper with your API keyapi=ApiNfl(api_key='YOUR_API_KEY')# Make your calls!teams=api.teams(league=api.Leagues.NFL)
Package: apisql
apisqlapisql is a flask blueprint providing an API for read-only access for a DBMS using direct SQL Queriesendpoints/queryReturns query results in json format.Query parameters that can be send:query: The SQL query to execute on the DB. The query can be provided in plain text or base64 encoded.num_rows: The maximum number of rows to return. If not specified, will return the aount defined in the configuration, the amount defined in the environment variableAPISQL__MAX_ROWSor 100.page_size: The size of the 'page', when doing paging. By default will usenum_rowsand in any way the page size it won't exceednum_rows.page: Which page to fetch, starting from page 0/downloadDownloads query results in either csv, xls or xlsx format.Query parameters that can be send:query: The SQL query to execute on the DB. The query can be provided in plain text or base64 encoded.format: Eithercsvorxlsx. Defaults tocsv.filename: The filename for the file to be downloaded,without the extension. Defaults toquery-results.headers: A semicolon separated list of the headers for the output file. Headers should match the field names that appear in the query.
Headers may contain one or more modifiers, which appear after a colon. The currently supported modifiers are:number, to convert numeric values to stringsyesno, which converts boolean values to "Yes" / "No"comma-separated, which converts arrays of strings to a comma separated list of these strings.
Finally, the content for a column may be fetched from a different field in the query output, by specifying the field name after a<character.Example:Fiscal Year:number<fiscal_year;Leap Year:yesno<0;Example:For the following SQL:select employee_name as "Employee Name", employee_salary as "Salary", is_manager as "Managerial role?" from employeesheaderscould be specified asEmployee Name;Managerial role?:yesno;Salary:number.configurationFlask configuration for this blueprint:fromapisqlimportapisql_blueprintapp.register_blueprint(apisql_blueprint(connection_string='psql://host/database',max_rows=1000,debug=False),url_prefix='/api/db/')