Saravanan666/pypi-org huggingface dataset:
Package: falcon-logger
Falcon LoggerThis is a python module that provides a way to run a fast logger.
Peregrine Falcons are the fastest anaimals alive (according to Google).
They go that fast by having as minimal drag as possible.Sample codesee sample.py for a full examplefromfalcon_loggerimportFalconLoggerSampleUse doit script to run the logger and compare against other loggers.To run the FalconLogger:./doitfalcon
./doitfalcon--numlines=100000To run the others loggers:./doitstdout# no file, just stdout./doitnormal# use the python logger./doitrsyslog# use the rsyslog python moduleComparing TimesThe overall time is very dependent on which OS you use and the speed of your computeron MSYS2 for 100,000 lines:
stdout: total time: 3170.0 ms
falcon: total time: 3623.9 ms
normal: total time: 5722.8 ms
rsyslog fails with an exception
Package: falcon-logging
Wrapper para trabalhar com a API do Cloud LoggingProcedimento para upload no PYPIPré requisitosInstalar pacotes pythonpython3 -m pip install --upgrade setuptools build wheel twineBuild e enviar ao PYPIpython3 -m buildpython3 -m twine upload dist/*Instalar o pacote no projetopip install falcon-loggingUtilização da bibliotecaEssa biblioteca espera que você passe o schema dos dados da tabela.É aconselhado criar um arquivo de schema.py ou model.py onde seja definido a estrutura de dados da tabela.Instanciar o MiddlewareCom o schema definido, você deve instanciar um classefromfalcon_logging.loggingimportLogMiddlewareimportfalconclassHealthCheckResource(object):defon_get(self,_,resp):"""Handles GET requests"""resp.status=falcon.HTTP_200resp.body='OK'defcreate():middlewares=[LogMiddleware()]_app=falcon.API(middleware=middlewares)_app.add_route('/',HealthCheckResource())return_appapp=create()Principais operaçõesUsando a classelogging, você pode executar algumas operações para auxiliar no desenvolvimento.Loggingfromfalcon_logging.loggingimportlogginglogging.info({"key":"value"})
Package: falcon-marshmallow
Falcon-Marshmallow is a middleware library designed to assist
developers who wish to easily incorporate automatic (de)serialization
using Marshmallow schemas into their Falcon application. Once
the middleware is in place, requests to any resources that have
aschemaattribute defined will automatically use that schema
to parse the request body. In addition, responses for that resource
will automatically use the defined schema to dump results.You may also specify method-specific schemas on a resource, e.g.patch_schema, which will be used only when the request method
matches the schema prefix.By default, this middleware will also automatically parse requests
and responses to JSON even if they do not have any schema(s) defined.
This can be easily disabled, if you would prefer to use your own JSON
parsing middleware. This is done usingsimplejsonby default,
but you may specify any module or object you like that implements
the public interface of the standard libraryjsonmodule.
Package: falcon-ml
FALCON: A Lightweight AutoML LibraryFalcon is a lightweight python library that allows to train production-ready machine learning models in a single line of code.Why Falcon ? 🔍Simplicity: With Falcon, training a comprehensive Machine Learning pipeline is as easy as writing a single line of code.Flexibility: Falcon offers a range of pre-set configurations, enabling swift interchangeability of internal components with just a minor parameter change.Extendability: Falcon's modular design, along with its extension registration procedure, allows seamless integration with virtually any framework.Portability: A standout feature of Falcon is its deep native support forONNXmodels. This lets you export complex pipelines into a single ONNX graph, irrespective of the underlying frameworks. As a result, your model can be conveniently deployed on any platform or with almost any programming language, all without dependence on the training environment.Future Developments 🔮Falcon ML is under active development. We've already implemented a robust and production-ready core functionality, but there's much more to come. We plan to introduce many new features by the end of the year, so stay tuned!⭐ If you liked the project, please support us with a star!Quick Start 🚀You can try falcon out simply by pointing it to the location of your dataset.fromfalconimportAutoMLAutoML(task='tabular_classification',train_data='/path/to/titanic.csv')Alternatively, you can use one of the available demo datasets.fromfalconimportAutoMLfromfalcon.datasetsimportload_churn_dataset,load_insurance_dataset# churn -> classification; insurance -> regressiondf=load_churn_dataset()AutoML(task='tabular_classification',train_data=df)Installation 💾Stable release fromPyPipipinstallfalcon-mlLatest version fromGitHubpipinstallgit+https://github.com/OKUA1/falconInstalling some of the dependencies onApple Silicon Macsmight not work, the workaround is to create an X86 environment usingCondacondacreate-nfalcon_env
condaactivatefalcon_env
condaconfig--env--setsubdirosx-64
condainstallpython=3.9
pip3installfalcon-mlDocumentation 📚You can find a more detailed guide as well as an API reference in ourofficial docs.Authors & Contributors ✨Oleg KostrominIryna KondrashchenkoMarco Pasini
Package: falcon-multipart
[![Build Status](https://travis-ci.org/yohanboniface/falcon-multipart.svg?branch=master)](https://travis-ci.org/yohanboniface/falcon-multipart)# Parse multipart/form-data requests in Falcon## Installpip install falcon-multipart## UsageAdd the `MultipartMiddleware` to your api middlewares:from falcon_multipart.middleware import MultipartMiddlewareapi = falcon.API(middleware=[MultipartMiddleware()])This will parse any `multipart/form-data` incoming request, and put the keysin `req._params`, including files, so you get the field as other params.## Dealing with filesFiles will be available as [`cgi.FieldStorage`](https://docs.python.org/3/library/cgi.html),with following main parameters:- `file`: act as a python file, you can call `read()` on it, and you willretrieve content (as *bytes*)- `filename`: the filename, if given- `value`: the file content in *bytes*- `type`: the content-type, or None if not specified- `disposition`: content-disposition, or None if not specified## Example# Say you have a form with those fields:# - title => a string# - image => an image filedef on_post(req, resp, **kwargs):title = req.get_param('title')image = req.get_param('image')# Read image as binaryraw = image.file.read()# Retrieve filenamefilename = image.filename
Package: falcon-oas
PrerequisitesValidated OpenAPI 3 documentfalcon-oas does not validate OpenAPI 3 document itself at runtime.  It should be validated in advance.FeaturesRequest validation and unmarshalingAccess controlAssociation of Path Item Objects and resource classes in FalconExampleclassPetItem:defon_get(self,req,resp,pet_id):pet=get_pet_by_id(pet_id)resp.media=pet.to_dict()defon_delete(self,req,resp,pet_id):pet=delete_pet_by_id(pet_id)resp.status=falcon.HTTP_NO_CONTENTwithopen('/path/to/openapi.json')asf:spec_dict=json.load(f)api=falcon_oas.OAS(spec_dict).create_api()Here is the part of its OpenAPI 3 document in YAML:paths:/api/v1/pets/{pet_id}:x-falcon-oas-implementation:path.to.PetItemget:responses:'200':description:A pet.delete:responses:'204':description:Successful deletion.security:-api_key:[]parameters:-name:pet_idin:pathrequired:trueschema:type:integercomponents:securitySchemes:api_key:x-falcon-oas-implementation:path.to.api_key_validatortype:apiKeyname:X-API-Keyin:headerpet_idpath parameter is unmarshaled tointwithoutField Converterssince it is defined asintegertype.DELETE/api/v1/pets/{pet_id}requests are protected by theapi_keysecurity scheme. The corresponding responder is processed only if it grants the request. Otherwise, 403 Forbidden error occurs automatically.x-falcon-oas-implementationassociates Path Item Object and the REST resource class in Falcon so that falcon-oas automatically callsfalcon.API.add_routewith its path and the resource instance. Alternatively, the resource instance can be set programmatically usingoas.resolve_path_item('/api/v1/pets/{pet_id}',PetItem()), which allows to inject dependencies into the resource instance.Alsox-falcon-oas-implementationassociates Security Scheme Object and the access control function so that falcon-oas automatically handles Security Requirement Object in each request. Seefalcon_oas.extensionsfor details. Alternatively, the access control function can be set programmatically usingoas.resolve_security_scheme('api_key',validate_api_key), which allows to inject dependencies into the access control function.req.context['oas']req.context['oas'].userAuthorized user.req.context['oas'].parametersUnmarshaled request parameters in dict.req.context['oas'].request_bodyUnmarshaled request body.ProblemsMedia Type:application/problem+jsononlyUnmarshal ErrorHTTP status code: 400"type":"https://pypi.org/project/falcon-oas/0.3.0/#unmarshal-error""title":"Unmarshal Error""status":400"parameters": (optional) The array of parameter error objects"request_body": (optional) The array of request body error objectsThe parameter error object and the request body error object have the following members fromjsonschema.ValidationError:"path": The path to the offending element within the instance"validator": The name of the failed validator"message": A human readable message explaining the errorExample:{"type":"https://pypi.org/project/falcon-oas/0.3.0/#unmarshal-error","title":"Unmarshal Error","status":400,"parameters":[{"path":["path","pet_id"],"validator":"type","message":"'me' is not of type 'integer'"}],"request_body":[{"path":["name"],"validator":"type","message":"42 is not of type 'string'"}]}
Package: falcon-observability
AIaaS Falcon ObservabilityFalcon ObservabilityThe Falcon Observability project is a Streamlit-based application designed for comprehensive log analytics and performance evaluation of AI models. This tool offers insightful visualizations and metrics derived from log data, enabling users to assess model behavior, track performance indicators, and conduct cost analysis for Azure services based on token usage.FeaturesLog Analytics and Visualization·Date Range Selection: Allows users to select date ranges for log analysis.·Time Filtering: Provides the option to filter logs based on specified start and end times.·Filter ID Input: Enables users to input a filter ID for more granular log retrieval.·Log Display: Renders log data in a table format using Streamlit'sst.data_editor.·Request Flow Visualization: Generates a line chart using Plotly Express to visualize the flow of requests over time.·Average Token Count Visualization: Displays the average token count over time in a line chart.Performance Analysis·Metrics Overview: Presents metrics such as total requests, average perplexity, toxicity, ARI (Automated Readability Index), Flesch-Kincaid Grade (FKG), total/request token count, and average token count.·Performance Metrics Visualization: Offers a detailed analysis of model performance metrics (e.g., Perplexity, Toxicity, ARI, FKG) over time through line chart visualizations.Cost Analysis (Azure)·Token-Based Cost Calculation: Computes and displays costs for Azure services based on token usage rates.·Price Visualization: Illustrates the calculated prices for request and response tokens in a line chart and table format.User Interface and Interaction·Sidebar Selection: Allows users to choose between 'Online' or 'Local' mode for log retrieval.·Form Submission: Utilizes Streamlit forms for submitting date range, time, and filter criteria.·Expander for Data Selection: Provides an expandable interface for users to select log data based on specified criteria.·Performance Analysis Trigger: Allows users to trigger the analysis of model performance metrics with a button click.Session State Management·State Persistence: Uses Streamlit's session state (st.session_state) to manage and update various analytics results, loading states, and dataframes.InstallationClone the repository and install the required dependencies:pip install falcon_observabilityUsageStarting the Servicefrom falcon_observability.main import FalconObservability
server=FalconObservability(port=8555)
server.start()Manage Serviceserver.status()Stop Serviceserver.stop()
Package: falcon-openapi
Falcon OpenApiFalcon OpenApi is a plugin for theFalcon Web Framework.Installpip3installfalcon-openapiOpenApi RouterReads an openapi spec and provides automatic routing to Falcon resources. This is achieved by defining either an operationId or x-falcon property on an endpoint. This removes the need to define all endpoints in your main Falcon file. Instead just set the router to OpenApiRouter.This router inherits from the default Falcon CompiledRouter class, so it supports all methods available to the default router.Supports json files, yaml files, raw json strings, and raw yaml strings. If no params are specified the plugin will attempt to findopenapi-spec.ymloropenapi-spec.yamlin the current working directory (see example for structure).importfalconimportjsonimportyamlfromfalcon_openapiimportOpenApiRouterspec={'paths':{'/foo':{'get':{'operationId':'controllers.foo.Foo.on_get'}}}}# load from fileapp=falcon.API(router=OpenApiRouter(file_path='openapi-spec.yml'))# load from raw jsonapp=falcon.API(router=OpenApiRouter(raw_json=json.dumps(spec)))# load from raw yamlapp=falcon.API(router=OpenApiRouter(raw_yaml=yaml.dump(spec)))operationIdThe example below will route allGET/foorequests tocontrollers.foo.Foo.on_get. Wherecontrollers.foois the module name,Foois the class name, andon_getis the method name. Every operationId in your spec should be unique (Seeopenapi operationId). All three parts of the operationId must be specified for the router to work.openapi:"3.0.0"info:version:1.0.0title:Falcon Openapi Demopaths:/foo:get:summary:Do foo thingsoperationId:controllers.foo.Foo.on_getI am unsure if operationId will make it into the final version. I may change this to only check for the x-falcon property. I plan on doing more research to determine if this an appropriate way to use theoperationId property.x-falconThe example below will route allPOST/foorequests to the modulecontrollers.foo, the classFoo, and the methodon_post. Note: the standard in Falcon is to use the naming scheme on_get, on_post, etc. If no method name is defined in x-falcon, the plugin will attempt to route to the appropriate on_* method.openapi:"3.0.0"info:version:1.0.0title:Falcon Openapi Demopaths:/foo:post:summary:Do foo thingsx-falcon:module:controllers.fooclass:Foomethod:on_post
Package: falcon-pagination
A small falcon hook to parse pagination elements from the request.For now it parses an Offset based pagination.UsageThe easiest way to use this hook is the following:@falcon.before(PaginationFromRequestHook())defon_get(self,req,resp,user):# Here req['context']['pagination'] is set# with 2 keys: 'offset' and 'limit'The Hook will look in the query parameters for 2 keys:offset: The pagination offsetlimit: The pagination limitIt will create a pagination dict into the request context accessible atreq.context['pagination'].
This pagination dict will contain 2 values:offset: The offset from the request or 0 if it doesn’t existslimit: The limit to apply. If no limit is found the default one is applied (20). If the value is bigger than the max value (100) then the default limit is also applied.Configuration optionsA few parameters can be passed to the hook:default_limit : The limit to apply if none is found in the request query or if the limit is out of bound. Default to 20max_limit: Maximum allowed limit. Default to 100offset_key: Name of the request parameter holding the offset value. Default to ‘offset’limit_key: Name of the request parameter holding the limit value. Default to ‘limit’Here’s an example setting a default limit to 10, a maximum limit to 500 the offset key to ‘page_offset’ and the limit key to ‘result_limit’:@falcon.before(PaginationFromRequestHook(default_limit=10,max_limit=500,offset_key='page_offset',limit_key='result_limit'))defon_get(self,req,resp,user):# Get request
Package: falcon-params-verifier
Falcon Query Parameter VerifierA simple falcon hook to check if a request contains all required query parameters.Installation / RequirementsInstallation:PyPipip install falcon_params_verifier.whlA.whlis provided in the releases tab in Github.Sample UsageSample codeimportfalconimportfalcon_params_verifierfromfalcon_params_verifierimportParamVerifier# This can also be used.classSampleResource(object):def__init__(self):self._required_params=["userId",]# Add the hook@falcon.before(falcon_params_verifier.ParamVerifier(self._required_params))defon_get(self,req,resp):req.media={"message":"Whoo hoo, you made a proper request!"}If a query parameter is missing, the module will automatically raise anfalcon.HTTPBadRequest.
Package: falcon-policy
Thefalcon-policypackage provides a middleware component
that enables simple policy controls such as role-based access on routes
via configuration.The configuration approach to policy rules enables dynamic authorization
use-cases where the policy needs to be adjusted on-demand without a new
service deployment.Installation$pipinstallfalcon-policyUsageTheRoleBasedPolicymiddleware class examines each incoming request
and verifies theroleslist from the request context; which should be
populated by an authentication middleware. If the request context isn’t
populated with aroleslist, then the middleware will fall back on
theX-Rolesheader for the appropriate role given the request being made.
Usage of theX-Rolesheader, is primarily used when handling
authentication outside of the middleware stack or for development with
authentication disabled.Implementation Note:If the request context type isn’t a dictionary, the middleware will assume
thatreq.contextis an Object with arolesattribute.Getting Started:Create a policy configurationCreate an instance ofRoleBasedPolicyusing the configurationPass the instance to thefalcon.API()initializer:fromfalcon_policyimportRoleBasedPolicypolicy_config={'roles':['admin','creator','observer',],'groups':{'create':['admin','creator'],'update':['admin','creator'],'read':['admin','creator','observer'],'delete':['admin'],},'routes':{'/quote':{'GET':['read'],'POST':['create'],'PUT':['update'],'DELETE':['delete'],},'/quote/{id}':{'GET':['read'],'POST':['create'],'PUT':['update'],'DELETE':['delete'],},'/status':{'GET':['@any-role'],'HEAD':['@passthrough'],},},}app=falcon.API(middleware=[RoleBasedPolicy(policy_config)])If validation fails an instance offalcon.HTTPForbiddenis raised.ConfigurationThe policy configuration is separated into three sections:Roles: Is a list of names that correspond with Role values provided
by your authentication system.Groups: Is an alias/grouping of multiple role names for convenience.Routes: A structure containing role and/or group permissions for a given
Falcon route and method.Specialty Roles:falcon-policyoffers two specialty roles types that should be used with
care:@any-role: Allows any defined role@passthrough: Allows all users (authenticated and unauthenticated)About FalconFalcon is abare-metal Python web
frameworkfor building lean and
mean cloud APIs and app backends. It encourages the REST architectural style,
and tries to do as little as possible while remaininghighly
effective.
Package: falcon-ratelimit
falcon-ratelimit================Rate limiter for Falcon. Install with:pipinstallfalcon-ratelimitUse like:importfalconfromfalconratelimitimportrate_limitclassNoRedisResource(object):@falcon.before(rate_limit(per_second=5,window_size=30,resource='resource_name'))defon_post(self,req,resp):...classRedisResource(object):@falcon.before(rate_limit(redis_url='localhost:6379',per_second=1,window_size=10))defon_post(self,req,resp):...This package works by limiting the number of requests using two variablesper_secondandwindow_size. In the first example above, theNoRedisResourceclass is restricted to 5 requests per second over a 30 secondwindow meaning that there is a limit of 150 requests over 30 seconds. Thedefault storage of calling therate_limitdecorator is an in memory list tostore the number of requests for the given user using the resourceresource_name.The second example implements the optional storage to use Redis by passing in aredis_urlto store user request data. Using Redis allows for the ratelimiting to be implemented across multiple instances of a particularapplication. In theRedisResourceclass example the user is allowed to make1 request per second over 10 seconds meaning that there is a limit of 10requests over 10 seconds. Since this example didn't pass in aresourceitusesdefaultas the name for request storage.If you do not have theredispackage installed, Redis-related functionalitywill not work.
Package: falcon-require-https
Thefalcon-require-httpspackage provides a middleware component
for sanity-checking that the incoming request was received over
HTTPS. While the web server is primarily responsibile for enforcing the
HTTPS protocol, misconfiguration is still a leading cause of security
vulnerabilities, and so it can be helpful to perform certain additional
checks, such as this one, within the application layer itself.Quick LinksView the code.Join the discussion group.Hang out in #falconframework on freenode.Installation$pipinstallfalcon-require-httpsUsageTheRequireHTTPSmiddleware class verifies each incoming request. To use
it, simply pass an instance to thefalcon.API()initializer:fromfalcon_require_httpsimportRequireHTTPSapp=falcon.API(middleware=[RequireHTTPS()])At least one of the following sources must indicate the use of HTTPS:The schema of the requested URLThe X-Forwarded-Proto headerThe Forwarded header (only the first hop is checked)Otherwise, an instance offalcon.HTTPBadRequestis raised.CautionThis middleware is not meant to replace proper security controls in your
web server or load balancer. It is simply meant as a final backstop to
guard against inadvertent misconfiguration at the networking layer.CreditsThis middleware component is based on paul291’s original
proof of concept, which was originally submitted as a PR to thefalconry/falconrepo.About FalconFalcon is abare-metal Python web
frameworkfor building lean and
mean cloud APIs and app backends. It encourages the REST architectural style,
and tries to do as little as possible while remaininghighly
effective.
Package: falcon-router
Falcon RouterSimple router lib forFalcon framework.IdeaFalcon's default router requires specifying routes by usingapp.add_route()syntax. While this
might not be a problem with small API's, it is not very friendly to repeat this line for large
API with over 50 routes. This is where Falcon Router comes in.FeaturesBoth ASGI and WSGI apps supportedSingle router file supportedMultiple router files/groups list supportedEnding trailing slash supportedUsageBasic (single route file) and advanced usage (multiple route groups/files) can be found underexamples.CreditsFalcon Router is heavily inspired byfalcon-url-versioningInstalling Falcon RouterFalcon Router is available on PyPI:$python-mpipinstallfalcon-router