Saravanan666/pypi-org huggingface dataset:
Package: apis-scraper
APiS-ScraperPLWeb scraper w Pythonie do pozyskiwania poparcia Polskich partii politycznych!Oto prosta biblioteka która pobiera stronehttp://ewybory.eu/sondaze(mam nadzieje że właściciele stronki nie mają nic przeciwko ;), i wyciąga z niej procenty poparcia poszczególnych partiiMożesz je wykorzystać do jakiegoś kreatywnego fajnego projektu :)Jak korzystać?Zainstaluj:pip3 install -U apis-scraperZaimportuj:import apis_scraperUżyj funkcjiapis_scraper.scrape(). Zwraca ona słownik, wyglądający tak:{'success':True,# Czy się udało, jeśli nie - False'support':{# Słownik z % poparcia - liczba z przecinkiem'pis':10.0,'ko':10.0,'lewica':10.0,'konfederacja':10.0,'psl':10.0,'polska2050':10.0},# Jeśli coś pójdzie nie tak, wszysktkie poparcia będą -1 a 'success' = False'growth':{# Czy poparcie rośnie/spada. -1=spada, 0=takie same, 1=rośnie'pis':0,'ko':0,'lewica':0,'konfederacja':0,'psl':0,'polska2050':0}}Przykładowy kod:importapis_scraperwyniki=apis_scraper.scrape()ifwyniki['success']==False:print('Nie dało rady - nie ma internetu czy coś :/')exit(-1)ifwyniki['support']['pis']<wyniki['support']['ko']:print('Trzeba anulować, bo przegramy...')Domyślnie, biblioteka zapisuje wyniki w plikuvote-results.json, żeby nie musiała zawsze pobierać strony z internetu - wyniki i tak zmieniają sie co ~tydzień.
Zapisane wyniki wyczerpują się po 24 godzinach.
Jeśli chcesz to zmienić, możesz:apis_scraper.scrape(no_cache=True,# Kompletenie wyłącza zapisywanie w pliku - nie polecamcache_file_name='dupa12.json',# Zmienia nazwe plikucache_expire_time=1*60*60# Zmienia czas (w sekundach) po którym plik sie wyczerpuje,# i strona jest pobierana na nowo)ENPython web scraper for getting Polish political parties support percentage!This is a simple library which downloads sitehttp://ewybory.eu/sondaze(I hope that administators don't mind ;) and scrapes support percentage of each party from itYou can then use it for some fun creative project ;)How to use?Install it:pip3 install -U apis-scraperImport it:import apis_scraperUse functionapis_scraper.scrape(). It returns a dict, which looks like this:{'success':True,# If it was succesfull, if not - False'support':{# Dict with % of support - in float'pis':10.0,'ko':10.0,'lewica':10.0,'konfederacja':10.0,'psl':10.0,'polska2050':10.0},# If something goes wrong, all supports will be -1 and 'success' = False'growth':{# Whether support is growing or falling. -1=falling, 0=stays same, 1=growing'pis':0,'ko':0,'lewica':0,'konfederacja':0,'psl':0,'polska2050':0}}Example code:importapis_scraperwyniki=apis_scraper.scrape()ifwyniki['success']==False:print("Can't do - no internet or something :/")exit(-1)ifwyniki['support']['pis']<wyniki['support']['ko']:print('We need to cancel, or we will lose...')By default, library saves results invote-results.jsonfile, so it doesn't need to download the site every time - results change ~once a week anyway.
Saved results expire after 24h
If you want to change this, you can:apis_scraper.scrape(no_cache=True,# Completley disable cache - not recommendedcache_file_name='dupa12.json',# Change file namecache_expire_time=1*60*60# Change time (in seconds) after file expires, and site is downloaded again)
Package: apist
Apist框架介绍apist致力于接口自动化，可以让测试员在不懂代码的情况下做接口自动化测试，只需要会excel以及遵循相应的规则即可。使用规范第一个sheet是你的所测系统的接口表格，里面放的是接口的各种信息。第二个sheet名为header，里面放cookie以及user-agent信息，用于请求的授权操作。第三个sheet名为email，里面放的是个人邮箱的用户名密码等信息，用于接收测试报告。详见excel模板中的示例。启动exe文件启动：api -f D://api.xls。项目中启动：from apist.apist import ApiApi('api.xls', is_email=False)
Package: apistar
🛠The Web API toolkit.🛠Community:https://discuss.apistar.org🤔 💭 🤓 💬 😎Documentation:https://docs.apistar.com📘Requirements:Python 3.6+API Star is a toolkit for working with OpenAPI or Swagger schemas. It allows you to:Build API documentation, with a selection of available themes.Validate API schema documents, and provide contextual errors.Make API requests using the dynamic client library.You can use it to build static documentation, integrate it within a Web framework,
or use it as the client library for interacting with other APIs.QuickstartInstall API Star:$pip3installapistarLet's take a look at some of the functionality the toolkit provides...We'll start by creating an OpenAPI schema,schema.yaml:openapi:3.0.0info:title:Widget APIversion:'1.0'description:An example API for widgetsservers:-url:https://www.example.org/paths:/widgets:get:summary:List all the widgets.operationId:listWidgetsparameters:-in:queryname:searchdescription:Filter widgets by this search term.schema:type:stringLet's also create a configuration fileapistar.yml:schema:path:schema.yamlformat:openapiWe're now ready to start using theapistarcommand line tool.We can validate our OpenAPI schema:$ apistar validate
✓ Valid OpenAPI schema.Or build developer documentation for our API:$ apistar docs --serve
✓ Documentation available at "http://127.0.0.1:8000/" (Ctrl+C to quit)We can also make API requests to the server referenced in the schema:$ apistar request listWidgets search=cogwheelWhere did the server go?With version 0.6 onwards the API Star project is being focused as a
framework-agnositic suite of API tooling. The plan is to build out this
functionality in a way that makes it appropriate for use either as a stand-alone
tool, or together with a large range of frameworks.The 0.5 branch remains available on GitHub, and can be installed from PyPI
withpip install apistar==0.5.41. Any further development of the API Star
server would likely need to be against a fork of that, under a new maintainer.If you're looking for a high-performance Python-based async framework, then
I would instead recommendStarlette.API Star isBSD licensedcode.Designed & built in Brighton, England.
Package: apistar-contrib
API Star ContribContrib packages to add on to API Star.Free software: MIT licenseDocumentation:https://api-star-contrib.readthedocs.io.FeaturesCSRF Token HookLocal Session Store (For Development)Timezone SupportRedis Session StoreTODODB Session StoreUsageLocal Session Store (For Development)fromapistarimportApp,Route,httpfromapistar_contrib.sessionsimportSession,SessionComponent,SessionHook,LocalMemorySessionStoredefuse_session(session:Session,params:http.QueryParams):forkey,valueinparams:session[key]=valuereturnsession.datadefclear_session(session:Session):session.clear()returnsession.dataroutes=[Route('/','GET',use_session),Route('/clear','GET',clear_session),]app=App(routes=routes,components=[SessionComponent(LocalMemorySessionStore)],event_hooks=[SessionHook])Redis Session StorefromapistarimportApp,Route,httpfromapistar_contrib.sessionsimportSession,SessionComponent,SessionHook,RedisSessionStoredefuse_session(session:Session,params:http.QueryParams):forkey,valueinparams:session[key]=valuereturnsession.datadefclear_session(session:Session):session.clear()returnsession.dataroutes=[Route('/','GET',use_session),Route('/clear','GET',clear_session),]app=App(routes=routes,components=[SessionComponent(RedisSessionStore,'redis://localhost:6379/0')],event_hooks=[SessionHook])CSRF TokenimportosfromapistarimportApp,Route,httpfromapistar_contrib.csrfimportEnforceCsrfHook,rotate_tokendefshow_form():returnapp.render_template('form.html',show_csrf=True,)defshow_no_csrf_form():returnapp.render_template('form.html',show_csrf=False,)defhandle_form(request:http.Request):# You should rotate CSRF tokens after successful login/logoutrotate_token(request)returnapp.render_template('form.html',show_csrf=True,success=True,)routes=[Route('/','GET',show_form),Route('/no_csrf','GET',show_no_csrf_form),Route('/handle','POST',handle_form),]BASE_DIR=os.path.dirname(__file__)TEMPLATE_DIR=os.path.join(BASE_DIR,'templates')app=App(routes=routes,event_hooks=[EnforceCsrfHook],template_dir=TEMPLATE_DIR,)<!-- templates/form.html --><!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><title>CSRF Form</title></head><body><ul><li><ahref="{{ reverse_url('show_form') }}">Form with CSRF</a></li><li><ahref="{{ reverse_url('show_no_csrf_form') }}">Form without CSRF</a></li></ul>{% if success %}<h1>Successful POST</h1>{% endif %}<formaction="{{ reverse_url('handle_form') }}"method="post">{% if show_csrf %} {{ csrf_token() }} {% endif %}<buttontype="submit">Submit form {% if show_csrf %}with{% else %}without{% endif %} CSRF</button></form></body></html>CreditsThis package was created withCookiecutterand theaudreyr/cookiecutter-pypackageproject template.History0.0.6 (2018-06-08)Added Redis Session Store to README and tests0.0.5 (2018-05-19)Added Redis Session StoreCreated first tests0.0.4 (2018-05-18)Remove default components0.0.3 (2018-05-18)Refactor Session component0.0.2 (2018-05-17)Add CSRF token hook0.0.1 (2018-05-15)First release on PyPI.
Package: apistar-cors-hooks
This project enables CORS onAPI Starapps via event hooks.Suppports:apistar>=0.4.0python>=3.6InstallationInstall via PyPI:pipinstallapistar_cors_hooksAfter installing, we need to add and instance ofCORSRequestHooksto yourevent_hooksin your app:fromapistarimportApp,Routefromapistar_cors_hooksimportCORSRequestHooksdefhomepage()->str:return'<html><body><h1>Homepage</h1></body></html>'routes=[Route('/',method='GET',handler=homepage),]event_hooks=[CORSRequestHooks()]app=App(routes=routes,event_hooks=event_hooks)If you want to customize WSGICORS options, you just need to pass a dict via theoptionskwarg:custom_options={"origin":"your_host_server"}event_hooks=[CORSRequestHooks(options=custom_options)]app=App(routes=routes,event_hooks=event_hooks)ContributingSince I’m a WSGI/CORS noob, I may have left a bug or two, or didn’t think of better ways to implement this.Be free to open an issue, contribute with PRs and contact me atluciano@ratamero.com.Changelog0.1.1adds README.rst as long description on PyPI0.1.0initial version
Package: apistar-mongoengine
Shameless bootleg copy offlask-mongoengineforAPI Star, modified for personal taste. Contributions are most welcome!Installation$pipinstallapistar-mongoengineGetting StartedFor your classes, useDocumentfromapistar_mongoengine.models.fromapistar_mongoengine.modelsimportDocumentfrommongoengineimportStringFieldclassTodoItem(Document):title=StringField(required=True)AddMongoClientComponentto your app’s components to initialize the mongodb connection.fromapistarimportApp,Routefromapistar_mongoengine.componentsimportMongoClientComponentfromyourapp.modelsimportTodoItemdeflist_items():return[item.titleforiteminTodoItem.objects.all()]routes=[Route(url='/items/',method='GET',handler=list_items),]components=[MongoClientComponent(host='mongodb://localhost:27017/todoapp'),]app=App(routes=routes,components=components)if__name__=='__main__':app.serve(host='127.0.0.1',port=5000,debug=True)Check theexamplefor more details.Running tests and getting the overall coverageInstall the required dependencies:$cd<projectdirectory>$pipenvinstallRunflake8:$pipenvrunflake8Runpytestwithcoverageflags:$pipenvrunpytest--cov-reporthtml--covapistar_mongoengine/--verboseOpen./htmlcov/index.htmlin your browser.ContributingImposter syndrome disclaimer: We want your help. No, really.There may be a little voice inside your head that is telling you that you’re not ready to be an open source contributor; that your skills aren’t nearly good enough to contribute. What could you possibly offer a project like this one?We assure you - the little voice in your head is wrong. If you can write code at all, you can contribute code to open source. Contributing to open source projects is a fantastic way to advance one’s coding skills. Writing perfect code isn’t the measure of a good developer (that would disqualify all of us!); it’s trying to create something, making mistakes, and learning from those mistakes. That’s how we all improve, and we are happy to help others learn.Being an open source contributor doesn’t just mean writing code, either. You can help out by writing documentation, tests, or even giving feedback about the project (and yes - that includes giving feedback about the contribution process). Some of these contributions may be the most valuable to the project as a whole, because you’re coming to the project with fresh eyes, so you can see the errors and assumptions that seasoned contributors have glossed over.LicenseMIT licensed. Please see the bundledLICENSE filefor more details.
Package: apistar-pagination
API Star PaginationVersion:0.4.0Status:Production/StableAuthor:José Antonio Perdiguero LópezPagination tools for API Star.FeaturesPage number pagination.Limit-offset pagination.Quick startInstall API star Pagination:pipinstallapistar-paginationUse paginated response in your views:Page number paginationfromapistar_paginationimportPageNumberResponsedefpage_number(page:http.QueryParam,page_size:http.QueryParam)->typing.List[int]:collection=range(10)# Get your whole collection instead of a list of numbersreturnPageNumberResponse(page=page,page_size=page_size,content=collection)Limit-offset paginationfromapistar_paginationimportLimitOffsetResponsedeflimit_offset(offset:http.QueryParam,limit:http.QueryParam)->typing.List[int]:collection=range(10)# Get your whole collection instead of a list of numbersreturnLimitOffsetResponse(offset=offset,limit=limit,content=collection)
Package: apistar-ponyorm
Third-party for apistar using pony ormLicense : GNU General Public License v3Documentation:https://apistar_ponyorm.readthedocs.org/en/latest/Source:https://github.com/jgirardet/apistar-ponyormFeaturesApistar Hook : PonyDBSession which give auto apply db_session to views.UsageThis should be added in App declaration :app = App(routes=[route], event_hooks=[PonyDBSession()])# main app.py filefromapistar_ponyormimportPonyDBSession# ...app=App(routes=[route],event_hooks=[PonyDBSession()])# myviews.pyfrommyprojectimportdb# PonyORM Database Instancedefmyviews():retundb.MyEntity.to_dict()# No need to add @db_sessionChangelog0.2.10 :use poetry0.2.0 :add PonyDBSession
Package: apistar-pydantic
Better handler parameters forAPIStar(andpydanticsupport).General usage is working as expected but documentation and OpenAPI schema aren’t done yet.$pipinstallapistar-pydanticUsagefromapistarimportAppfrompydanticimportBaseModelfromapistar_pydanticimport(QueryParam,PathParam,DictBodyData,DictQueryData,PydanticBodyDataasBodyData,PydanticQueryDataasQueryData,Route,components,)## Declare models#classCity(BaseModel):"""City info"""name:strpopulation:intclassComputer(BaseModel):"""Computer info"""model:strprice:floatclassComputerCity(City,Computer):"""A computer in a city"""## Create views#defresource_complete(param1:QueryParam[str],param2:QueryParam[int],param3:DictBodyData[dict],param4:DictQueryData[dict]):returnrepr(locals())defresource_query(city:QueryData[City]):return"%shas%dcitizens."%(city.name,city.population)defresource_body(computer:BodyData[Computer]):return"%scosts R$%.2f"%(computer.model,computer.price)defresource_mixed(city:QueryData[City],computer:BodyData[Computer]):returnComputerCity(**city.dict(),**computer.dict())## Start the app#app=App(routes=[Route('/resource','GET',resource_query),Route('/resource_query','GET',resource_query),Route('/resource_body','POST',resource_body),Route('/resource_mixed','POST',resource_mixed),],components=[*components])if__name__=='__main__':app.serve('127.0.0.1',3000,debug=True)
Package: apistar-sqlalchemy
Version:0.3.2Status:Production/StableAuthor:José Antonio Perdiguero LópezSQLAlchemy integration for API Star.FeaturesThis library providescomponentsfor injecting SQLAlchemy ORM sessions into your views andevent_hooksto
handle commit/rollback behavior based on exceptions in your views.Quick startInstall API Star SQLAlchemy:pipinstallapistar-sqlalchemyCreate an API Star application adding components and event hooks:fromapistar_sqlalchemy.componentsimportSQLAlchemySessionComponentfromapistar_sqlalchemy.event_hooksimportSQLAlchemyTransactionHookroutes=[]components=[SQLAlchemySessionComponent(url='sqlite://'),]event_hooks=[SQLAlchemyTransactionHook(),]app=App(routes=routes,components=components,event_hooks=event_hooks)Now you can inject SQLAlchemy Session into your views:fromsqlalchemy.ormimportSessiondefsqlalchemy_view(session:Session):# do somethingreturn{'message':'something done'}Forget aboutcommitandrollbackbecause there is an event hook that will handle it for you.Full examplefromtypingimportListfromapistarimportApp,Route,http,types,validatorsfromsqlalchemyimportColumn,Integer,Stringfromsqlalchemy.ormimportSessionfromapistar_sqlalchemy.componentsimportSQLAlchemySessionComponentfromapistar_sqlalchemy.event_hooksimportSQLAlchemyTransactionHookfromapistar_sqlalchemyimportdatabaseclassPuppyModel(database.Base):__tablename__="Puppy"id=Column(Integer,primary_key=True,autoincrement=True)name=Column(String)classPuppyType(types.Type):id=validators.Integer(allow_null=True,default=None)name=validators.String()deflist_puppies(session:Session)->List[PuppyType]:return[PuppyType(puppy)forpuppyinsession.query(PuppyModel).all()]defcreate_puppy(session:Session,puppy:PuppyType)->http.JSONResponse:model=PuppyModel(**puppy)session.add(model)session.flush()returnhttp.JSONResponse(PuppyType(model),status_code=201)routes=[Route('/puppy/','POST',create_puppy),Route('/puppy/','GET',list_puppies),]components=[SQLAlchemySessionComponent(url='sqlite://'),]event_hooks=[SQLAlchemyTransactionHook(),]app=App(routes=routes,components=components,event_hooks=event_hooks)
Package: apistats
APIStatsSimple django module with a middleware to track calls to django backend.DescriptionAPIStats is a middleware that stores basic information on the requests and responses to Django backend.Installationpip install apistatsAddapistatstoINSTALLED_APPSRun./manage.py migrateAdd'apistats.middlewares.LoggingMiddleware'toMIDDLEWAREinsettings.pyUsageAPIstats adds an admin interface to :view / sort / filter recordsview detail of a record and statisticsModelAPIStats stores the following fields:user: user account making the requestrecord_time: time of the recordmethod: method of the requestdomain: first part of the request pathpath: complete pathquery: query parameters for GET requestsip: IP of the callerdelay: nb of milliseconds between request and responsestatus: response HTTP status
Package: api_stats
api_stats is a Python tool aimed at recording statistics from an API endpoint. For example, the GitHub API gives out a single number of downloads for each release; by running this tool, you can easily graph rolling averages and historical figures.Quickstartapi_stats loads a “configuration file” that tells it what to fetch and which fields to record. This file is a Python script that will be loaded by api_stats, with a single globalstatsthat acts as the interface with the program. This interface currently offers two functions:record(key, value), andget_json(url).Here is an example configuration file, that records the number of downloads of each file from GitHub releases:releases=stats.get_json("https://api.github.com/repos/remram44/api_stats/releases")forreleaseinreleases:relname=release.get('tag_name')orrelease['name']forassetinrelease['assets']:stats.record('%s/%s'%(relname,asset['name']),asset['download_count'])Then you can plot the data, for example using matplotlib:python-mapi_stats.plot-m'^(.+)$''api_stats:\g<1>'data.jsonlA more complex exampleYou might want to use functions to factor the retrieval of data points from a specific source:defgithub(repo):releases=stats.get_json("https://api.github.com/repos/%s/releases"%repo)forreleaseinreleases:ifrelease['draft']:continuerelname=release.get('tag_name')orrelease['name']forassetinrelease['assets']:stats.record('github/%s/%s/%s'%(repo,relname,asset['name']),asset['download_count'])github('VisTrails/VisTrails')github('remram44/api_stats')defpypi(pkg):releases=stats.get_json("https://pypi.python.org/pypi/%s/json"%pkg)['releases']forrelname,releaseinreleases.items():forassetinrelease:stats.record('pypi/%s/%s/%s'%(pkg,relname,asset['filename']),asset['downloads'])pypi('VisTrails')pypi('api_stats')This will record data underpypi/<pkg_name>/<version>/<filename>andgithub/<owner>/<repo>/<version>/<filename>. You can then plot the data, one figure per project, aggregated by version but adding PyPI and GitHub together, using:python-mapi_stats.plot\-m'^pypi/([^/]+)/([^/]+)/.+$''\g<1>:\g<2>'\-m'^github/[^/]+/([^/]+)/v([^/]+)/.+$''\g<1>:\g<2>'\releases.jsonl
Package: api-status
StatusSimple way to make a /status for your services with python and asyncio.Installpipinstallapi-statusHow it works ?TL;DR;Check a working example at:https://gitlab.com/cdlr75/status/-/blob/develop/tests/learning/example.pyLet say you have a coroutine that replies a dict with the desired status of your service:asyncdefstatus():""" Returns our service status.:returns: Misc info about our service.:rtype: dict"""return{"name":"MyService","status":"ok","version":"v1"}Withapi-status, to expose this through an HTTP endpoint:fromstatusimportServerserver=Server(host="127.0.0.1",port=8080)# register our status endpointserver.add_route(status,method="GET",path=r"/status")awaitserver.start()# the status is now available at http://127.0.0.1:8080/statusIf you take care of graceful shutdowns for your services, call the methodstop:awaitserver.stop()
Package: apistellar
apistellar WEB框架BadgeGitHubPyPiDescapistellar是基于apistar的web构建工具，同时增强了apistar的功能，使用apistellar可以轻松构建适合生产环境的web项目。apistellar部分设计灵感参考ruby on rails除了apistar本身的特性以外，apistellar增加如下几点高级用法：CSM架构，将控制层，业务层，模型层完全分离，耦合性降至最低。模板式定制各类模型，轻松扩展模型定义的模板类。适配sphinx注释语法，使用构建命令一键生成api文档和RPC-client。集成flask版的session实现。自带一些event hook，轻松集成异常、session处理。集成配置模块，集中管理所有配置信息。离线任务管理，同一web服务下的离线任务，轻松复用web模块定义的model, service等等可注入对象。模板一键创建。集成IPython交互式命令行工具，自动注入model, service等对象。提供异步代码执行能力，轻松调试各模块。提供上传文件流对象，对大文件上传完美支持。Apistar作者在uvicorn中提供了websocket支持，但是未集成到apistar中，apistellar对二者进行了集成，完美支持websocket。Install# python 3.6+
pip install apistellarDoc目录Quick Startapistellar项目组成model的使用方法controller的使用方法service的使用方法Session管理使用require实现简单session认证增强的EventHook错误码处理配置信息管理自定义项目构建任务solo任务(离线任务)使用集成的IPython进行异步代码的调试大文件上传下载使用websocket进行通讯使用apistellar测试插件pytest-apistellar进行单元测试model持久化方案API接口文档自动生成RESTFul RPC客户端驱动包一键生成全局对象参考资料asgi web框架 APIStar----终于等到你...妈妈再也不用担心我不写文档了，RESTful API文档一键生成！RESTful服务构建利器apistellar深度剖析asgi协议
Package: apistellar-cas
CAS for apistellarUSEAGEpip install apistellar-casfromapistellar_casimportnit# before app initinit()...fromapistarimportAppfromapistellarimportController,route,getfromapistellar_casimportlogin_required@route("/",name="welcome")classWelcomeController(Controller):@get("/")@login_required()# add thisdefindex(self,app:App)->str:returnapp.render_template('index.html')# settings.pyCAS_SERVER='https://xxx.xxx.xxx'CAS_LOGIN_ROUTE='/xxxx'CAS_AFTER_LOGIN='view:welcome:index'CAS_USERNAME_SESSION_KEY="username"
Package: apiStock
API STOCKApi Useful To Get Historical Stock Price ValuesInstallationAPI STOCK requiresPython 3to run.
Installpip install apiStockFeatured MethodsgetStockHistory(code, start_date, end_date)code stock in Vietnam Stock Market.start_date should be entered in the ‘YYYY-MM-DD’ format and is the first day that data will be pulled for.end_date should be entered in the ‘YYYY-MM-DD’ format and is the last day that data will be pulled for.UsefromapiStockimportgetStockHistoryvin_prices=getStockHistory('VIN','2019-08-19','2020-08-19')LicenseMITFree Library, Hell Yeah!