package
stringlengths 1
122
| pacakge-description
stringlengths 0
1.3M
|
---|---|
aiogram-tools | aiogram_tools |
aiogram-translation | Aiogram Translation Plugin 🌐About 📘The Aiogram Translation Plugin is a convenient and powerful tool for integrating multilingual support into Aiogram-based Telegram bots. It enables seamless translation and language handling, making your bot accessible to a wider, global audience.Installation 📥python-mpipinstall-Uaiogram-translationUsage 🛠️To use the Aiogram Translation Plugin in your bot, import the necessary classes fromaiogram_translation. Set up your languages, default language, and register the translator with your dispatcher. Here's a basic example:main.pyfromaiogramimportDispatcher,Bot,Ffromaiogram.typesimportMessage,InlineKeyboardMarkup,InlineKeyboardButton,CallbackQueryfromaiogram_translationimportTranslatorfromtranslationsimport*fromosimportgetenvbot=Bot(getenv("TELEGRAM_TOKEN"))dispatcher=Dispatcher()translator=Translator()translator.include([English(),Russian(),Ukrainian()])translator.set_default('ru')translator.register(dispatcher)@dispatcher.message()asyncdefon_message(message:Message,language:BaseTranslation):kb=InlineKeyboardMarkup(resize_keyboard=True,inline_keyboard=[[InlineKeyboardButton(text=language.start_button,callback_data="hoooray")]])awaitmessage.reply(language.start_message,reply_markup=kb)@dispatcher.callback_query(F.data=="hoooray")asyncdefon_hooray(query:CallbackQuery,language:BaseTranslation):awaitquery.answer(language.start_button_alert,show_alert=True)dispatcher.run_polling(bot)translations.pyfromaiogram_translation.modelsimportBaseTranslationBuilderclassBaseTranslation(BaseTranslationBuilder):start_message:strstart_button:strstart_button_alert:strlink_lang_message:strclassEnglish(BaseTranslation):key="en"name="English"start_message="👋 Hi, I'm bot!"start_button="❤️ Click me!"start_button_alert="🎉 Hooray!"classRussian(BaseTranslation):key="ru"name="Русский (Russian)"start_message="👋 Привет, я бот"start_button="❤️ Нажми на меня"start_button_alert="🎉 Ура!"classUkrainian(BaseTranslation):key="uk"name="Український (Ukrainian)"start_message="👋 Привіт, я бот"start_button="❤️ Натисни на мене"start_button_alert="🎉 Ура!"Troubleshooting 🚨If you encounter issues or have queries, feel free to check ourIssues sectionon GitHub.Contribution 🤝Contributions are welcome. Please fork the repository, make your changes, and submit a pull request.License 📜This project is licensed under the MIT License - see theLICENSEfile for details. |
aiogram-unittest | aiogram_unittestaiogram_unittestis a testing library for bots written onaiogram📚 Simple examplesSimple handler testSimple bot:fromaiogramimportBot,Dispatcher,types,executor# Please, keep your bot tokens on environments, this code only examplebot=Bot('123456789:AABBCCDDEEFFaabbccddeeff-1234567890')dp=Dispatcher(bot)@dp.message_handler()asyncdefecho(message:types.Message):awaitmessage.answer(message.text)if__name__=='__main__':executor.start_polling(dp)Test cases:importunittestfrombotimportechofromaiogram_unittestimportRequesterfromaiogram_unittest.handlerimportMessageHandlerfromaiogram_unittest.types.datasetimportMESSAGEclassTestBot(unittest.IsolatedAsyncioTestCase):asyncdeftest_echo(self):request=Requester(request_handler=MessageHandler(echo))calls=awaitrequest.query(message=MESSAGE.as_object(text="Hello, Bot!"))answer_message=calls.send_messsage.fetchone()self.assertEqual(answer_message.text,'Hello, Bot!')▶️Moreexamples |
aiogram-uptodate | Aiogram UptodateThis project, a fork ofnoXplode/aiogram_calendar, introduces an intuitive and user-friendly calendar and timesheet for Telegram bots using theaiogramframework in Python.What's Inside?Dual Calendar Modes:Choose between comprehensive navigation or dialog-based selection.Hide Unnecessary Dates:Effortlessly conceal dates that are not requiredDate Range Limitation:Restrict date selection within a specific range.TimeSheet Dialog: Allows users to select a time slot after picking a date for easy scheduling.Highlight Today's Date:Easily identify the current date.Localisation Support:Customize the language or inherit from the user's locale settings.Compatibility:Aiogram 3:Fully supported from version 0.2 (for Aiogram 2 use version 0.1.1)Installationpipinstallaiogram_uptodate |
aiogram-utils | TODO |
aiogram-widgets | aiogram_widgetsCreate most popular widgets for aiogram 3x in a few code lines🔗 LinksFeaturesFully customizable widgetsStatelessAutomatic handlingSupports aiogram ^3.0.0b1RoadmapCheckboxes and multiselectCalendarAiogram 2x supportChangelogVersion 1.2.7:Fixed a bug that still requiredpagination_keyoptionVersion 1.2.6:Fixed a bug that caused uncompability in python versions 3.10 and lowerVersion 1.2.5:Added the ability to adjust buttons passing tuple of sizes (works the similar way as in InlineKeyboardBuilder.adjust) in keyboard paginationVersion 1.2.4:Fixed aiogram dependency bugVersion 1.2.3:Fixed typings at Python 3.9pagination_keyoption now is not requiredBetter types namingVersion 1.2.2:Custom pagination keyboard supportAiogram 3.0.0b8 supportREADME with more examplesLive bot example with source codeBetter types namingInstallationPip:pipinstallaiogram_widgetsPoetry:poetryaddaiogram_widgets🤖Bot example|Bot source code⚙️Usage/ExamplesSimple keyboard paginationfromaiogram_widgets.paginationimportKeyboardPaginator@router.message(F.text=="/keyboard_pagination")asyncdefkeyboard_pagination(message:Message):buttons=[InlineKeyboardButton(text=f"Button{i}",callback_data=f"button_{i}")foriinrange(1,1001)]paginator=KeyboardPaginator(data=buttons,per_page=20,per_row=2)awaitmessage.answer(text="Keyboard pagination",reply_markup=paginator.as_markup())Keyboard pagination with additional buttons (Same with text pagination)fromaiogram_widgets.paginationimportKeyboardPaginator@router.message(F.text=="/kb_additional_buttons")asyncdefkb_additional_buttons(message:Message):buttons=[InlineKeyboardButton(text=f"Button{i}",callback_data=f"button_{i}")foriinrange(1,1001)]additional_buttons=[[InlineKeyboardButton(text="Go back 🔙",callback_data="go_back"),]]paginator=KeyboardPaginator(data=buttons,additional_buttons=additional_buttons,per_page=20,per_row=2)awaitmessage.answer(text="Keyboard pagination with additional buttons",reply_markup=paginator.as_markup(),)Keyboard pagination with custom pagination buttons (Same with text pagination)@router.message(F.text=="/kb_custom_pagination")asyncdefkb_custom_pagination(message:Message):text_data=[f"I am string number{i}"foriinrange(1,1001)]pagination_buttons=[None,"<-","->",None]paginator=TextPaginator(data=text_data,pagination_buttons=pagination_buttons,)current_text_chunk,reply_markup=paginator.current_message_dataawaitmessage.answer(text=current_text_chunk,reply_markup=reply_markup,)Simple text paginationfromaiogram_widgets.paginationimportTextPaginator@router.message(F.text=="/text_pagination")asyncdeftext_pagination(message:Message):text_data=[f"I am string number{i}"foriinrange(1,1001)]paginator=TextPaginator(data=text_data,)current_text_chunk,reply_markup=paginator.current_message_dataawaitmessage.answer(text=current_text_chunk,reply_markup=reply_markup,)Text pagination with custom [email protected](F.text=="/text_join")asyncdeftext_custom_join(message:Message):text_data=[f"I am string number{i}"foriinrange(1,1001)]paginator=TextPaginator(data=text_data,join_symbol="\n\n",)current_text_chunk,reply_markup=paginator.current_message_dataawaitmessage.answer(text=current_text_chunk,reply_markup=reply_markup,)FeedbackI would be very pleased for a star ⭐️ |
aiogram_windows | # aiogram_windows |
aiogram-ydb-storage | aiogram YDB Storageaiogram_ydb_storageis a storage implementation foraiogram FSMthat utilizes Yandex Database (YDB) as the storage backend. This allows you to persist state data for state machines used in your Telegram bots.InstallationYou can installaiogram_ydb_storagevia pip:pipinstallaiogram_ydb_storageUsageTo useaiogram_ydb_storage, you need to first set up your YDB database and obtain necessary credentials. Then, you can use it in conjunction withaiogramas follows:importasynciofromaiogramimportBot,Dispatcher,typesfromaiogram.filtersimportCommandStartfromaiogram.typesimportMessagefromaiogram.fsm.contextimportFSMContextfromaiogram.fsm.stateimportStatesGroup,Stateimportydbfromaiogram_ydb_storageimportYDBStorage# Configure YDB driverdriver_config=ydb.DriverConfig("grpcs://...",# YDB endpoint"...",# Database namecredentials=ydb.credentials_from_env_variables(),# Use YDB credentials from environment)# Initialize YDBStoragemy_storage=YDBStorage(driver_config=driver_config)# Initialize aiogram Bot and Dispatcherdp=Dispatcher(storage=my_storage)bot=Bot("token")# Define your statesclassMyStates(StatesGroup):test1=State()test2=State()# [email protected](CommandStart())asyncdefcommand_start_handler(message:Message,state:FSMContext)->None:awaitstate.set_state(MyStates.test1)awaitmessage.answer("Set state test1")@dp.message(MyStates.test1)asyncdefhandler(message:types.Message,state:FSMContext)->None:awaitmessage.answer("state test1. Set state test2")awaitstate.set_state(MyStates.test2)@dp.message()asyncdefecho_handler(message:types.Message,state:FSMContext)->None:awaitmessage.answer("not state test1. Set state test1")awaitstate.set_state(MyStates.test1)# Main functionasyncdefmain()->None:awaitdp.start_polling(bot)# Run the main functionif__name__=="__main__":asyncio.run(main())ContributingContributions are welcome! Please feel free to submit issues or pull requests.LicenseThis project is licensed under the MIT License - see theLICENSEfile for details. |
aiograph | aiograph- asynchronous Python Telegra.ph API wrapper.AnnotationsThe Telegraph class (aiograph.Telegraph) encapsulates all API calls in a single class.
It provides functions such as create_page, get_views and other’s methods described atTelegra.ph/apipageAll data types stored In the packageaiograph.types.All methods are named following thePEP-8instructions
for examplecreate_accountforcreateAccountmethod and etc.
All API methods are awaitable and can be called only inside Event-loop.Also if you want to upload the file to Telegra.ph service useuploadmethod
from the instance of Telegraph class.By the end of all actions you will need to close HTTP connections by calling theclose()method (is awaitable).InstallationUsing PIP$pipinstall-UaiographFrom sources$gitclonehttps://github.com/aiogram/aiograph.git$cdaiograph$pythonsetup.pyinstallUsage examplesBasicsimportasynciofromaiographimportTelegraphloop=asyncio.get_event_loop()telegraph=Telegraph()asyncdefmain():awaittelegraph.create_account('aiograph-demo')page=awaittelegraph.create_page('Demo','<p><strong>Hello, world!</strong></p>')print('Created page:',page.url)if__name__=='__main__':try:loop.run_until_complete(main())except(KeyboardInterrupt,SystemExit):passfinally:loop.run_until_complete(telegraph.close())# Close the aiohttp.ClientSessionLinksNews:@aiogram_liveCommunity:@aiogramRussian community:@aiogram_ruPip:aiographSource:Github repoIssues/Bug tracker:Github issues tracker |
aiographfix | aiographfix- asynchronous Python Telegra.ph API wrapper, that fix aiographAnnotationsThe Telegraph class (aiographfix.Telegraph) encapsulates all API calls in a single class.
It provides functions such as create_page, get_views and other’s methods described atTelegra.ph/apipageAll data types stored In the packageaiographfix.types.All methods are named following thePEP-8instructions
for examplecreate_accountforcreateAccountmethod and etc.
All API methods are awaitable and can be called only inside Event-loop.Also if you want to upload the file to Telegra.ph service useuploadmethod
from the instance of Telegraph class.By the end of all actions you will need to close HTTP connections by calling theclose()method (is awaitable).InstallationUsing PIP$pipinstall-UaiographfixFrom sources$gitclonehttps://github.com/Yyonging/aiograph.git$cdaiograph$pythonsetup.pyinstallUsage examplesimportasynciofromaiographfiximportTelegraphloop=asyncio.get_event_loop()telegraph=Telegraph()asyncdefmain():awaittelegraph.create_account('aiograph-demo')page=awaittelegraph.create_page('Demo','<p><strong>Hello, world!</strong></p>')print('Created page:',page.url)if__name__=='__main__':try:loop.run_until_complete(main())except(KeyboardInterrupt,SystemExit):passfinally:loop.run_until_complete(telegraph.close())# Close the aiohttp.ClientSessionLinksNews:@aiogram_liveCommunity:@aiogramRussian community:@aiogram_ruPip:aiographfixSource:Github repoIssues/Bug tracker:Github issues tracker |
aiographfixed | aiographfix- asynchronous Python Telegra.ph API wrapper, that fix aiographAnnotationsThe Telegraph class (aiographfixed.Telegraph) encapsulates all API calls in a single class.
It provides functions such as create_page, get_views and other’s methods described atTelegra.ph/apipageAll data types stored In the packageaiographfixed.types.All methods are named following thePEP-8instructions
for examplecreate_accountforcreateAccountmethod and etc.
All API methods are awaitable and can be called only inside Event-loop.Also if you want to upload the file to Telegra.ph service useuploadmethod
from the instance of Telegraph class.By the end of all actions you will need to close HTTP connections by calling theclose()method (is awaitable).InstallationUsing PIP$pipinstall-UaiographfixedFrom sources$gitclonehttps://github.com/Lunatik-cyber/aiographfixed.git$cdaiographfixed$pythonsetup.pyinstallUsage examplesimportasynciofromaiographfixedimportTelegraphloop=asyncio.get_event_loop()telegraph=Telegraph()asyncdefmain():awaittelegraph.create_account('aiograph-demo')page=awaittelegraph.create_page(title='Demo',content='<p><strong>Hello, world!</strong></p>',public=True)print('Created page:',page.url)if__name__=='__main__':try:loop.run_until_complete(main())except(KeyboardInterrupt,SystemExit):passfinally:loop.run_until_complete(telegraph.close())# Close the aiohttp.ClientSessionLinksNews:@aiogram_liveCommunity:@aiogramRussian community:@aiogram_ruPip:aiographfixSource:Github repoIssues/Bug tracker:Github issues tracker |
aiographite | An asyncio library for graphite.You can find out more here:http://aiographite.readthedocs.io/en/latest/What is aiographite ?aiographite is Python3 library ultilizing asyncio, designed
to help Graphite users to send data into graphite easily.Installing it globallyYou can install aiographite globally with any Python package manager:pip install aiographiteQuick startLet’s get started.from aiographite import connect
from aiographite.protocol import PlaintextProtocol
"""
Initialize a aiographite instance
"""
loop = asyncio.get_event_loop()
plaintext_protocol = PlaintextProtocol()
graphite_conn = await connect(*httpd.address, plaintext_protocol, loop=loop)
"""
Send a tuple (metric, value , timestamp)
"""
await graphite_conn.send(metric, value, timestamp)
"""
Send a list of tuples List[(metric, value , timestamp)]
"""
await graphite_conn.send_multiple(list)
"""
aiographite library also provides GraphiteEncoder module,
which helps users to send valid metric name to graphite.
For Example: (metric_parts, value ,timestamp)
"""
metric = graphite_conn.clean_and_join_metric_parts(metric_parts)
await graphite_conn.send(metric, value, timestamp)
"""
Close connection
"""
await graphite_conn.close()ExampleA simple example.from aiographite.protocol import PlaintextProtocol
from aiographite import connect
import time
import asyncio
LOOP = asyncio.get_event_loop()
SERVER = '127.0.0.1'
PORT = 2003
async def test_send_data():
# Initiazlize an aiographite instance
plaintext_protocol = PlaintextProtocol()
graphite_conn = await connect(SERVER, PORT, plaintext_protocol, loop=LOOP)
# Send data
timestamp = time.time()
for i in range(10):
await graphite_conn.send("yun_test.aiographite", i, timestamp + 60 * i)))
def main():
LOOP.run_until_complete(test_send_data())
LOOP.close()
if __name__ == '__main__':
main()DevelopmentRun unit tests../uranium testGraphite setupDo not have graphite instances ? Set up a graphite instance on your local machine!Please refer:https://github.com/yunstanford/MyGraphitehttps://github.com/yunstanford/GraphiteSetup |
aiographql | asyncio- explicit concurrencyto reduce race conditionsgraphql- all you need and nothing more in one request +auto docs of your apiuvloop, protocol-top performanceminimal http - unlike REST frameworks that are waste of time for/graphqlendpointpluggable context - for auth, logging, etcexception handling - at all levels, with default or custom handlerUsage:pip install aiographql
cat <<'END' >serve.py
import asyncio, aiographql, graphene
class User(graphene.ObjectType):
id = graphene.ID(required=True)
name = graphene.String()
class Query(graphene.ObjectType):
me = graphene.Field(User)
async def resolve_me(self, info):
await asyncio.sleep(1) # DB
return User(id=42, name='John')
schema = graphene.Schema(query=Query, mutation=None)
aiographql.serve(schema, listen=[
dict(protocol='tcp', port=25100),
dict(protocol='unix', path='/tmp/worker0'),
])
END
python3 serve.py
curl http://localhost:25100/ --data-binary \
'{"query": "{
me {
id
name
}
}", "variables": null}'
# OR:
curl --unix-socket /tmp/worker0 http:/ --data-binary ...
# Result:
# 1 second async await for DB and then:
{"data":{"me":{"id":"42","name":"John"}}}Seemore examples and testsabout JWT auth, concurrent slow DB queries, etc.Config:import aiographql; help(aiographql.serve)
serve(schema, listen, get_context=None, exception_handler=None, enable_uvloop=True, run=True)
Configure the stack and start serving requestsschema:graphene.Schema- GraphQL schema to servelisten:list- one or more endpoints to listen for connections:dict(protocol='tcp',port=25100,...)-create_server() docsdict(protocol='unix',path='/tmp/worker0',...)-create_unix_server() docsget_context:Noneor[async] callable(loop, context: dict): mixed- to produce GraphQL context like auth from input unified withexception_handler()exception_handler:Noneorcallable(loop, context: dict)- default or custom exception handler as defined inthe docs+headers:bytesorNone- HTTP headers, if knownrequest:dictorbytesorNone- accumulated HTTP request before content length is known, then accumulated content, then GraphQL requestenable_uvloop:bool- enable uvloop for top performance, unless you have a better looprun:bool- ifTrue, run the loop;Falseis good for testsreturnservers:Servers-await servers.close()to close listening sockets - good for tests |
aiographql-client | Asynchronous GraphQL ClientAn asynchronous GraphQL client built on top of aiohttp and graphql-core-next. The client by default introspects schemas and validates all queries prior to dispatching to the server.DocumentationFor the most recent project documentation, you can visithttps://aiographql-client.readthedocs.io/.Installationpip install aiographql-clientExample UsageHere are some example usages of this client implementation. For more examples, and advanced scenarios,
seeUsage Examplessection in
the documentation.Simple Queryasyncdefget_logged_in_username(token:str)->GraphQLResponse:client=GraphQLClient(endpoint="https://api.github.com/graphql",headers={"Authorization":f"Bearer{token}"},)request=GraphQLRequest(query="""query {viewer {login}}""")returnawaitclient.query(request=request)>>> import asyncio>>> response = asyncio.run(get_logged_in_username("<TOKEN FROM GITHUB GRAPHQL API>"))>>> response.data{'viewer': {'login': 'username'}}Query Subscriptionasyncdefprint_city_updates(client:GraphQLClient,city:str)->None:request=GraphQLRequest(query="""subscription ($city:String!) {city(where: {name: {_eq: $city}}) {descriptionid}}""",variables={"city":city},)# subscribe to data and error events, and print themawaitclient.subscribe(request=request,on_data=print,on_error=print,wait=True)For custom event specific callback registration, seeCallback Registry Documentation.Query Validation FailuresIf your query is invalid, thanks to graphql-core-next, we get a detailed exception in the traceback.aiographql.client.exceptions.GraphQLClientValidationException: Query validation failed
Cannot query field 'ids' on type 'chatbot'. Did you mean 'id'?
GraphQL request (4:13)
3: chatbot {
4: ids, bot_names
^
5: }
Cannot query field 'bot_names' on type 'chatbot'. Did you mean 'bot_name' or 'bot_language'?
GraphQL request (4:18)
3: chatbot {
4: ids, bot_names
^
5: }Query Variables & OperationsSupport for multi-operation requests and variables is available via the client. For example,
the following request contains multiple operations. The instance specifies default values to use.request=GraphQLRequest(query="""query get_bot_created($id: Int) {chatbot(where: {id: {_eq: $id}}) {id, created}}query get_bot_name($id: Int) {chatbot(where: {id: {_eq: $id}}) {id, bot_name}}""",variables={"id":109},operation="get_bot_name")The default values can be overridden at the time of making the request if required.awaitclient.query(request=request,variables={"id":20},operation="get_bot_created") |
aiograpi | Asynchronous Instagram Private API wrapper.Use the most recent version of the API from Instagram.Features:Performs Public API (web, anonymous) or Private API (mobile app, authorized)
requests depending on the situation (to avoid Instagram limits)Challenge Resolver have Email (as well as recipes for automating receive a code from email) and SMS handlersSupport upload a Photo, Video, IGTV, Clips (Reels), Albums and StoriesSupport work with User, Media, Insights, Collections, Location (Place), Hashtag and Direct objectsLike, Follow, Edit account (Bio) and much more elseInsights by account, posts and storiesBuild stories with custom background, font animation, swipe up link and mention users |
aiogremlin | AIO GremlinAn asynchronous DSL for the Gremlin-Python driverLicensed under the Apache Software License v2aiogremlinis an asynchronous DSL based on the officialGremlin-PythonGLV designed for integration with
event loop based asynchronous Python networking libraries, includingasyncio,aiohttp, andtornado. It uses theasync/awaitsyntax introduced
in PEP 492, and is therefore Python 3.5+ only.aiogremlintries to followGremlin-Pythonas closely as possible both in terms
of API and implementation. It is released according to the TinkerPop release schedule.aiogremlinis built directly on top of TinkerPop and allows access to all of the internals. This ensures all the
TinkerPop features are available to the end-user. The TinkerPop stack provides several tools which can be used to work
withaiogremlin.Gremlin, a database agnostic query language for Graph Databases.Gremlin Server, a server that provides an interface for executing Gremlin on remote machines.a data-flow framework for splitting, merging, filtering, and transforming of dataGraph Computer, a framework for running algorithms against a Graph Database.Support for bothOLTPandOLAPengines.TinkerGrapha Graph Database and the reference implementation for TinkerPop.NativeGephiintegration for visualizing graphs.Interfaces for most major Graph Compute Engines includingHadoop M/R.Spark, andGiraph.aiogremlinalso supports any of the many databases compatible with TinkerPop including the following.JanusGraphTitanNeo4jOrientDBMongoDBOracle NoSQLTinkerGraphSome unique feature provided by the Goblin OGM include:High level asynchronousObject Graph Mapper(OGM) - provided bygoblinIntegration with theofficial gremlin-python Gremlin Language Variant(GLV)Native Python support for asynchronous programing includingcoroutines,iterators, andcontext managersas specified inPEP 492Asynchronous Python driverfor the Gremlin ServerAsyncGraphimplementation that producesnative Python GLV traversalsGetting StartedimportasynciofromaiogremlinimportDriverRemoteConnection,Graphloop=asyncio.get_event_loop()asyncdefgo(loop):remote_connection=awaitDriverRemoteConnection.open('ws://localhost:8182/gremlin','g')g=Graph().traversal().withRemote(remote_connection)vertices=awaitg.V().toList()awaitremote_connection.close()returnverticesvertices=loop.run_until_complete(go(loop))print(vertices)# [v[1], v[2], v[3], v[4], v[5], v[6]]DonatingAs an open-source project we run entierly off donations. Buy one of our hardworking developers a beer by donating with one of the above buttons. All donations go to our bounty fund and allow us to place bounties on important bugs and enhancements.Support and DocumentationThe official homepage for the project is athttp://goblin-ogm.com. The source is officially hosted onQOTO GitLab herehowever an up-to-date mirror is also maintained onGithub here.Documentation:latestFor support please useGitteror theofficial Goblin mailing list and Discourse forum.Please file bugs and feature requests onQOTO GitLabour old archived issues can still be viewed onGithubas well.Aparapi conforms to theSemantic Versioning 2.0.0standard. That means the version of a release isnt arbitrary but rather describes how the library interfaces have changed. Read more about it at theSemantic Versioning page.Related ProjectsThis particular repository only represents the one component in a suite of libraries. There are several other related repositories worth taking a look at.Goblin- The main library, the Goblin OGMGoblin Buildchain- Docker image containing all the needed tools to build and test Goblin.Python Gremlin Server- Vanilla Gremlin-server with Python Script Engine loaded, used for integration testing. |
aiogrn | asyncioGroongaClient.RequirementsPython3.5+UsageGQTPimportasynciofromaiogrn.clientimportGroongaClientasyncdeffetch(grn,cmd,**kwargs):ret=awaitgrn.call(cmd,**kwargs)print(ret)loop=asyncio.get_event_loop()grn=GroongaClient(host='localhost',port=10043,protocol='gqtp',loop=loop)tasks=[asyncio.ensure_future(fetch(grn,'status')),asyncio.ensure_future(fetch(grn,'select',table='Foo')),asyncio.ensure_future(fetch(grn,'status'))]loop.run_until_complete(asyncio.gather(*tasks))loop.close()HTTPimportasynciofromaiogrn.clientimportGroongaClientasyncdeffetch(grn,cmd,**kwargs):ret=awaitgrn.call(cmd,**kwargs)print(ret)loop=asyncio.get_event_loop()grn=GroongaClient(loop=loop)tasks=[asyncio.ensure_future(fetch(grn,'status')),asyncio.ensure_future(fetch(grn,'select',table='Foo')),asyncio.ensure_future(fetch(grn,'status'))]loop.run_until_complete(asyncio.gather(*tasks))loop.close() |
aiogrobid | aiogrobidAsynchronous client for Grobid APIExampleimportasynciofromaiogrobidimportGrobidClientasyncdefworks(doi):client=GrobidClient()returnawaitclient.works(doi)response=asyncio.get_event_loop().run_until_complete(works('10.21100/compass.v11i2.812'))assert(response=={'DOI':'10.21100/compass.v11i2.812','ISSN':['2044-0081','2044-0073'],'URL':'http://dx.doi.org/10.21100/compass.v11i2.812','abstract':'<jats:p>Abstract: Educational policy and provision is ''ever-changing; but how does pedagogy need to adapt to respond ''to transhumanism? This opinion piece discusses transhumanism, ''questions what it will mean to be posthuman, and considers the ''implications of this on the future of education.</jats:p>','author':[{'affiliation':[],'family':'Gibson','given':'Poppy Frances','sequence':'first'}],'container-title':['Compass: Journal of Learning and Teaching'],'content-domain':{'crossmark-restriction':False,'domain':[]},'created':{'date-parts':[[2018,12,17]],'date-time':'2018-12-17T09:42:26Z','timestamp':1545039746000},'deposited':{'date-parts':[[2019,6,11]],'date-time':'2019-06-11T10:29:57Z','timestamp':1560248997000},'indexed':{'date-parts':[[2020,4,14]],'date-time':'2020-04-14T14:52:16Z','timestamp':1586875936184},'is-referenced-by-count':0,'issn-type':[{'type':'print','value':'2044-0073'},{'type':'electronic','value':'2044-0081'}],'issue':'2','issued':{'date-parts':[[2018,12,10]]},'journal-issue':{'issue':'2','published-online':{'date-parts':[[2018,12,10]]}},'link':[{'URL':'https://journals.gre.ac.uk/index.php/compass/article/viewFile/812/pdf','content-type':'application/pdf','content-version':'vor','intended-application':'text-mining'},{'URL':'https://journals.gre.ac.uk/index.php/compass/article/viewFile/812/pdf','content-type':'unspecified','content-version':'vor','intended-application':'similarity-checking'}],'member':'8854','original-title':[],'prefix':'10.21100','published-online':{'date-parts':[[2018,12,10]]},'publisher':'Educational Development Unit, University of Greenwich','reference-count':0,'references-count':0,'relation':{},'score':1.0,'short-container-title':['Compass'],'short-title':[],'source':'Crossref','subtitle':[],'title':['From Humanities to Metahumanities: Transhumanism and the Future ''of Education'],'type':'journal-article','volume':'11'}) |
aiogrouper | # aiogrouperThis is a library for interacting with Internet2’s Grouper in asynchronous code.You may also be interested in [Robert Bradley](https://github.com/rb12345)’s[grouper_ws](https://github.com/rb12345/grouper_ws) package on which this was
based. |
aiogrpc | No description available on PyPI. |
aiogrpcclient | # AIO GRPC ClientAbstract class for creating GRPC API clients |
aiogrpctools | No description available on PyPI. |
aiogtrans | aiogtransaiogtrans is afreeandunlimitedpython library that implements the Google Translate API asynchronously. This uses theGoogle Translate Ajax APIandhttpxto make api calls.Compatible with Python 3.6+.For details refer to theAPI Documentation.FeaturesFast and semi-reliableUses the same api that google translate usesReverse EngineeredAuto language detectionBulk translationsCustomizable service URLHTTP/2 supportHTTP/2 supportThis library uses httpx for HTTP requests so HTTP/2 is supported by default.You can check if http2 is enabled and working by the._response.http_versionofTranslatedorDetectedobject:>>>(awaittranslator.translate('테스트'))._response.http_version# 'HTTP/2'How does this library work?You may wonder why this library works properly, whereas other approaches such like goslate won't work since Google has updated its translation service recently with a ticket mechanism to prevent a lot of crawler programs.The original fork authorSuhun Haneventually figured out a way to generate a ticket by reverse engineering the obfuscated and minified code used by Google to generate tokenshttps://translate.google.com/translate/releases/twsfe_w_20170306_RC00/r/js/desktop_module_main.js>, and implemented this in Python. However, this could be blocked at any time.Why not use googletrans?It seemsSuhun Hanhas abandoned the project, at the time of this writing it's been nearly a year and a half since the last commit.I have decided to move on and update this project.Installation$pipinstallaiogtransBasic UsageIf a source language is not given, google translate attempts to detect the source language.>>>fromaiogtransimportTranslator>>>translator=Translator()>>>awaittranslator.translate('안녕하세요.')# <Translated src=ko dest=en text=Good evening. pronunciation=Good evening.>>>>awaittranslator.translate('안녕하세요.',dest='ja')# <Translated src=ko dest=ja text=こんにちは。 pronunciation=Kon'nichiwa.>>>>awaittranslator.translate('veritas lux mea',src='la')# <Translated src=la dest=en text=The truth is my light pronunciation=The truth is my light>Customize service URLYou can use another google translate domain for translation. If multiple URLs are provided, the program will randomly choose a domain.>>>fromaiogtransimportTranslator>>>translator=Translator(service_urls=['translate.google.com','translate.google.co.kr',])Advanced Usage (Bulk Translations)You can provide a list of strings to be used to translated in a single method and HTTP session.>>>translations=awaittranslator.translate(['The quick brown fox','jumps over','the lazy dog'],dest='ko')>>>fortranslationintranslations:...print(translation.origin,' -> ',translation.text)# The quick brown fox -> 빠른 갈색 여우# jumps over -> 이상 점프# the lazy dog -> 게으른 개Language DetectionThe detect method, as its name implies, identifies the language used in a given sentence.>>>fromgoogletransimportTranslator>>>translator=Translator()>>>awaittranslator.detect('이 문장은 한글로 쓰여졌습니다.')# <Detected lang=ko confidence=0.27041003>>>>awaittranslator.detect('この文章は日本語で書かれました。')# <Detected lang=ja confidence=0.64889508>>>>awaittranslator.detect('This sentence is written in English.')# <Detected lang=en confidence=0.22348526>>>>awaittranslator.detect('Tiu frazo estas skribita en Esperanto.')# <Detected lang=eo confidence=0.10538048>aiogtrans as a command line application$translate-h
usage:translate[-h][-dDEST][-sSRC][-c]text
PythonGoogleTranslatorasacommand-linetool
positionalarguments:textThetextyouwanttotranslate.
optionalarguments:-h,--helpshowthishelpmessageandexit-dDEST,--destDESTThedestinationlanguageyouwanttotranslate.(Default:en)-sSRC,--srcSRCThesourcelanguageyouwanttotranslate.(Default:auto)-c,--detect
$translate"veritas lux mea"-sla-den[veritas]veritasluxmea->[en]Thetruthismylight[pron.]Thetruthismylight
$translate-c"안녕하세요."[ko,1]안녕하세요.Note on Library UsageDISCLAIMER: this is an unofficial library using the web API of translate.google.com and also is not associated with Google.The maximum character limit on a single text is 15,000.Due to limitations of the web version of google translate, this API does not guarantee that the library would work properly at all times (so please use this library if you don't care about stability).Important:If you want to use a stable API, it is highly recommended that you use Google's official translate APIhttps://cloud.google.com/translate/docs.If you get HTTP 5xx error or errors like #6, it's probably because Google has banned your client IP address.ContributingContributions are currently discouraged, I am writing this fork as a personal project and if I ever do decide to open up to contributions I will change this.Of course you're more then welcome to fork this and make your own changesLicenseaiogtransis licensed under the MIT License. The terms are as follows:The MIT License (MIT)Copyright (c) 2022 Ben ZhouPermission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE. |
aiogTTS | aiogTTSaiogTTS(asynchronous Google Text-to-Speech), a Python library to interface with Google Translate's text-to-speech API.
Writes spoken mp3 data to a file or a file-like object (bytestring) for further audiomanipulation.Original gTTS -https://github.com/pndurette/gTTS/(75% of this repo)FeaturesCustomizable speech-specific sentence tokenizer that allows for unlimited lengths of text to be read, all while keeping proper intonation, abbreviations, decimals and more;Customizable text pre-processors which can, for example, provide pronunciation corrections;Installation$pipinstallaiogTTSQuickstartimportasynciofromioimportBytesIOfromaiogttsimportaiogTTSasyncdefmain():aiogtts=aiogTTS()io=BytesIO()awaitaiogtts.save('Привет, мир!','audio.mp3',lang='ru')awaitaiogtts.write_to_fp('Hallo!',io,slow=True,lang='de')asyncio.get_event_loop().run_until_complete(main()) |
aioguardian | 🚰 aioguardian: A Python3 library for Elexa Guardian devicesaioguardianis a Python3,asyncio-focused library for interacting withthe Guardian line of water valves and sensors from Elexa.InstallationPython VersionsDocumentationContributingInstallationpipinstallaioguardianPython Versionsaioguardianis currently supported on:Python 3.10Python 3.11Python 3.12DocumentationComplete documentation can be foundhere.ContributingThanks to all ofour contributorsso far!Check for open features/bugsorinitiate a discussion on one.Fork the repository.(optional, but highly recommended) Create a virtual environment:python3 -m venv .venv(optional, but highly recommended) Enter the virtual environment:source ./.venv/bin/activateInstall the dev environment:script/setupCode your new feature or bug fix on a new branch.Write tests that cover your new functionality.Run tests and ensure 100% code coverage:poetry run pytest --cov aioguardian testsUpdateREADME.mdwith any new documentation.Submit a pull request! |
aioguest | Trio, an alternate async framework
for Python, supports a feature called“guest mode”where it can run in the same thread as
another event loop. In guest mode, low-level I/O waiting occurs on a worker thread,
but the threading is invisible to user code, and both event loops can interact
with each other without any special synchronization.This package implements guest mode for asyncio. It has one public function:aioguest.start_guest_run(
coro,
*,
run_sync_soon_threadsafe,
done_callback,
run_sync_soon_not_threadsafe=None,
debug=None,
loop_factory=None,
)This effectively starts a call toasyncio.run(coro)in parallel
with the currently running (“host”) event loop. Thedebugparameter
is passed toasyncio.run()if specified. On Python 3.11+, you can
also supply aloop_factorywhich will be passed toasyncio.Runner().The parametersrun_sync_soon_threadsafe,done_callback, and (optionally)run_sync_soon_not_threadsafetellaioguesthow to interact with the host
event loop. Somedayaioguestwill have documentation of its own.
Until then, see theTrio documentationfor details on these parameters, including anexample.start_guest_run()returns the main task of the new asyncio run, i.e.,
theasyncio.Taskthat wrapscoro. It may also return None if the main task
could not be determined, such as becauseasyncio.run()raised an exception
before starting to executecoro. The main task is provided mostly for
cancellation purposes; while you can also register callbacks upon its completion,
the run is not necessarily finished at that point, because background tasks and
async generators might still be in the process of finalization.Exceptions noticed when starting up the asyncio run might either propagate out ofstart_guest_run()or be delivered to yourdone_callback, maybe even beforestart_guest_run()returns (it will return None in that case). In general,
problems noticed byaioguestwill propagate out ofstart_guest_run(),
while problems noticed by asyncio will be delivered to yourdone_callback.aioguestrequires Python 3.8 or later. Out of the box it supports
the default asyncio event loop implementation (only) on Linux,
Windows, macOS, FreeBSD, and maybe others. It does not support
operating systems that provide onlyselect()orpoll(); due to
thread-safety considerations it needs an I/O abstraction where the OS
kernel is involved in registrations, such as IOCP, epoll, or kqueue.
Alternative Python-based event loops can likely be supported given
modest effort if they use such an abstraction. Alternative C-based
event loops (such as uvloop) present much more of a challenge because
compiled code generally can’t be monkeypatched.Development statusaioguesthas been tested with a variety of toy examples and
pathological cases, and its unit tests exercise full coverage. It
hasn’t had a lot of exposure to real-world problems yet. Maybe you’d
like to expose it to yours?Licenseaioguestis licensed under your choice of the MIT or Apache 2.0
license. SeeLICENSEfor details. |
aioh2 | aioh2HTTP/2 implementation withhyper-h2on Python 3 asyncio.Free software: BSD licenseDocumentation:https://aioh2.readthedocs.org.FeaturesAsynchronous HTTP/2 client and serverMultiplexing streams of data with managed flow and priority controlOptional tickless health checkMore to comeNon-features:Request/Response wrappersWeb server, dispatcher, cookie, etcHTTP/2 upgradeExampleA server saying hello:# Server request handlerasyncdefon_connected(proto):try:whileTrue:# Receive a request from queuestream_id,headers=awaitproto.recv_request()# Send response headersawaitproto.start_response(stream_id,{':status':'200'})# Response body starts with "hello"awaitproto.send_data(stream_id,b'hello, ')# Read all request body as a name from client sidename=awaitproto.read_stream(stream_id,-1)# Amend response body with the nameawaitproto.send_data(stream_id,name)# Send trailers with the length of the nameawaitproto.send_trailers(stream_id,{'len':str(len(name))})exceptasyncio.CancelledError:# do cleanup herepass# Start server on random port, with maximum concurrent requests of 3server=awaitaioh2.start_server(on_connected,port=0,concurrency=3)port=server.sockets[0].getsockname()[1]And a client to try out:# Open client connectionclient=awaitaioh2.open_connection('0.0.0.0',port,functional_timeout=0.1)# Optionally wait for an ack of tickless ping - a.k.a. until functionalawaitasyncio.sleep(0.1)# simulate client being busy with something elsertt=awaitclient.wait_functional()ifrtt:print('Round-trip time:%.1fms'%(rtt*1000))# Start request with headersstream_id=awaitclient.start_request({':method':'GET',':path':'/index.html'})# Send my name "world" as whole request bodyawaitclient.send_data(stream_id,b'world',end_stream=True)# Receive response headersheaders=awaitclient.recv_response(stream_id)print('Response headers:',headers)# Read all response bodyresp=awaitclient.read_stream(stream_id,-1)print('Response body:',resp)# Read response trailerstrailers=awaitclient.recv_trailers(stream_id)print('Response trailers:',trailers)client.close_connection()awaitasyncio.sleep(.1)Above example can be found atexamples/core.py.CreditsA big thanks to the great libraryhyper-h2fromCory Benfield.DecentFoX Studiois a software outsourcing company delivering high-quality
web-based products and mobile apps for global customers with agile methodology,
focusing on bleeding-edge technologies and fast-developing scalable architectures.This package was created withCookiecutterand theaudreyr/cookiecutter-pypackageproject template.History0.2.1 (2017-12-03)Updated to h2 3.0 (Contributed by Arthur Darcet and Peter Wu)Dropped support for Python 3.30.1.0 (2016-2-6)First release on PyPI. |
aiohandler | aiohandleraiohandler = aiohttp http handleraiohandler is a logging extension module.By using this module, logs can be sent by webhook.installingInstall and update using pip:pip install aiohandlerA simple example.Enter the parameters required for sending the webhook in the body.importasyncioimportloggingimportaiohandlerWEBHOOK_URL="Your webhook url"logger=logging.getLogger()handler=aiohandler.AioHTTPHandler(WEBHOOK_URL,method="POST",body="content")logger.addHandler(handler)loop=asyncio.get_event_loop()asyncdefmain():print("hello!")logging.info('info')logging.debug('debug')logging.error('error')awaitasyncio.sleep(1)logging.warning('warning')logging.critical('critical')print("hello world!")if__name__=="__main__":loop.create_task(main())loop.run_forever()Thank you to everyone who Helped me (#^^#) |
aiohap | Failed to fetch description. HTTP Status Code: 404 |
aiohappybase | AIOHappyBaseis a developer-friendlyPythonlibrary to interact asynchronously with ApacheHBase. It is a fork of the originalHappyBaselibrary aiming to deliver a very similar API.Documentation(Docs)Downloads(PyPI)Source code(Github) |
aiohappyeyeballs | aiohappyeyeballsDocumentation:https://aiohappyeyeballs.readthedocs.ioSource Code:https://github.com/aio-libs/aiohappyeyeballsHappy EyeballsUse caseThis library exists to allow connecting with Happy Eyeballs when you
already have a list of addrinfo and not a DNS name.The stdlib version ofloop.create_connection()will only work when you pass in an unresolved name which
is not a good fit when using DNS caching or resolving
names via another method such waszeroconf.InstallationInstall this via pip (or your favourite package manager):pip install aiohappyeyeballsExample usageaddr_infos=awaitloop.getaddrinfo("example.org",80)socket=awaitstart_connection(addr_infos)socket=awaitstart_connection(addr_infos,local_addr_infos=local_addr_infos,happy_eyeballs_delay=0.2)transport,protocol=awaitloop.create_connection(MyProtocol,sock=socket,...)# Remove the first address for each family from addr_infopop_addr_infos_interleave(addr_info,1)# Remove all matching address from addr_inforemove_addr_infos(addr_info,"dead::beef::")# Convert a local_addr to local_addr_infoslocal_addr_infos=addr_to_addr_infos(("127.0.0.1",0))CreditsThis package contains code from cpython and is licensed under the same terms as cpython itself.This package was created withCopierand thebrowniebroke/pypackage-templateproject template. |
aioharmony | Python library for programmatically using a Logitech Harmony Link or Ultimate Hub.This library originated fromiandday/pyharmonywhich was a fork
ofbkanuka/pyharmonywith the intent to:Make the harmony library asyncioAbility to provide one’s own custom callbacks to be calledAutomatic reconnect, even if re-connection cannot be established for a timeMore easily get the HUB configuration through API callAdditional callbacks: connect, disconnect, HUB configuration updatedUsing unique msgid’s ensuring that responses from the HUB are correctly managed.ProtocolAs the harmony protocol is being worked out, notes will be in PROTOCOL.md.StatusRetrieving current activityQuerying for entire device informationQuerying for activity information onlyQuerying for current activityStarting ActivitySending CommandChanging channelsCustom callbacks.Usageusage:__main__.py[-h](--harmony_ipHARMONY_IP|--discover)[--protocol{WEBSOCKETS,XMPP}][--loglevel{DEBUG,INFO,WARNING,ERROR,CRITICAL}][--logmodulesLOGMODULES][--show_responses|--no-show_responses][--waitWAIT]{show_config,show_detailed_config,show_current_activity,start_activity,power_off,sync,listen,activity_monitor,send_command,change_channel}...aioharmony-Harmonydevicecontrolpositionalarguments:{show_config,show_detailed_config,show_current_activity,start_activity,power_off,sync,listen,activity_monitor,send_command,change_channel}show_configPrinttheHarmonydeviceconfiguration.show_detailed_configPrintthedetailedHarmonydeviceconfiguration.show_current_activityPrintthecurrentactivityconfig.start_activitySwitchtoadifferentactivity.power_offStoptheactivity.syncSynctheharmony.listenOutputeverythingHUBsendsout.Useincombinationwith--wait.activity_monitorMonitorandshowwhenanactivityischanging.Useincombinationwith--waittokeepmonitoringforactivitiesotherwiseonlycurrentactivitywillbeshown.send_commandSendasimplecommand.send_commandsSendaseriesofsimplecommandsseparatedbyspaces.change_channelChangethechanneloptionalarguments:-h,--helpshowthishelpmessageandexit--harmony_ipHARMONY_IPIPAddressoftheHarmonydevice,multipleIPscanbespecifiedasacommaseparatedlistwithoutspaces.(default:None)--discoverScanforHarmonydevices.(default:False)--protocol{WEBSOCKETS,XMPP}ProtocoltousetoconnecttoHUB.NoteforXMPPonehastoensurethatXMPPisenabledonthehub.(default:None)--loglevel{DEBUG,INFO,WARNING,ERROR,CRITICAL}Logginglevelforallcomponentstoprinttotheconsole.(default:ERROR)--logmodulesLOGMODULESRestrictloggingtomodulesspecified.Multiplecanbeprovidedasacommaseparatedlistwithoutanyspaces.Use*toincludeanyfurthersubmodules.(default:None)--show_responsesPrintoutresponsescomingfromHUB.(default:False)--no-show_responsesDonotprintresponsescomingfromHUB.(default:False)--waitWAITHowlongtowaitinsecondsaftercompletion,usefulincombinationwith--show-responses.Use-1towaitinfinite,otherwisehastobeapositivenumber.(default:0)Release Notes0.1.0. Initial Release0.1.2. Fixed:Enable callback connect only once initial connect and initialization is completed.Fix exception when activity/device name/id is None when trying to retrieve name/id.Fixed content type and name of README in setup.py0.1.3. Fixed:Retry connect on reconnect0.1.4. Fixed:Exception when retrieve_hub_info failed to retrieve informationcall_callback helper would never return True on success.Retry connect on reconnect (was not awaited upon)0.1.5. Fixed:Exception when an invalid command was sent to HUB (or sending command failed on HUB).Messages for failed commands were not printed in main.0.1.6. Fixed:Ignore response code 200 when for sending commandsUpon reconnect, errors will be logged on 1st try only, any subsequent retry until connection is successful will
only provide DEBUG log entries.0.1.7. Fixed:Fix traceback if no configuration retrieved or items missing from configuration (i.e. no activities)Retrieve current activity only after retrieving configuration0.1.8. Fixed:NOTE: This version will ONLY work with 4.15.250 or potentially higher. It will not work with lower versions!Fix traceback if HUB info is not received.Fix for new HUB version 4.15.250. (Thanks toreneboerfor providing the quick fix).0.1.9. Fixed:Fixed “Network unreachable” or “Host unreachable” on certain installations (i.e. in Docker, HassIO)0.1.10. Changed:On reconnect the wait time will now start at 1 seconds and double every time with a maximum of 30 seconds.Reconnect sometimes might not work if request to close was received over web socket but it never was closed.0.1.11. Changed:Timeout changed from 30 seconds to 5 seconds for network activity.For reconnect, first wait for 1 second before starting reconnects.0.1.12. Fixed/Changed:Fixed issue where connection debug messages would not be shown on failed reconnects.Added debug log entry when connected to HUB.0.1.13.Fixed further potential issue where on some OS’s sockets would not be closed by now force closing them.0.2.0. New:Support for XMPP. If XMPP is enabled on Hub then that will be used, otherwise fallback to web sockets.
There are no changes to the API for this. XMPP has to be explicitly enabled on the Harmony HUB.
To do so open the Harmony app and go to: Menu > Harmony Setup > Add/Edit Devices & Activities > Remote & Hub > Enable XMPP
Same steps can be followed to disable XMPP again.Log entries from responsehandler class will now include ip address of HUB for easier identification0.2.1 Fixed:Fixed issue in sending commands to HUB wbe using XMPP protocol.0.2.2 Fixed:Added closing code from aiohttp for web sockets in debug logging if closing code provided.Fixed further potential issue where on some OS’s sockets would not be closed by now force closing them (merge from 0.1.13)Fixed listen parameter as it would just exit instead of continuously wait.0.2.3 Changed:Updated requirement for slixmpp to 1.5.2 as that version works with Home Assistant0.2.4 Fixed:Friendly Name of Harmony HUB was not retrieved anymore, this is now available againRemote ID was not retrieved anymore, this is now available againIf HUB disconnects when retrieving information then retrieval will be retried.Executing aioharmony with option show_detailed_config will now show all config retrieved from HUB0.2.5Fixed: When using XMPP protocol the switching of an activity was not always discovered.Fixed: Call to stop handlers will now be called when timeout occurs on disconnectChanged: ClientCallbackType is now in aioharmony.const instead of aioharmony.harmonyclient.Changed: default log level for aioharmony main is now ERRORNew: callback option new_activity_starting to allow a callback when a new activity is being started (new_activity is called when switching activity is completed)New: 3 new HANDLER types have been added:HANDLER_START_ACTIVITY_NOTIFY_STARTED: activity is being startedHANDLER_STOP_ACTIVITY_NOTIFY_STARTED: power off is startedHANDLER_START_ACTIVITY_NOTIRY_INPROGRESS: activity switch is in progressNew: Protocol to use can be specified (WEBSOCKETS or XMPP) to force specific protocol to be used. If not provided XMPP will be used unless not available then WEBSOCKETS will be used.New: protocol used to connect can now be retrieved. It will return WEBSOCKETS when connected over web sockets or XMPP.New: One can now supply multiple IP addresses for Harmony HUBs when using aioharmony main.New: option activity_monitor for aioharmony main to allow just monitoring of activity changesNew: option logmodules for aioharmony main to specify the modules to put logging information for0.2.6Changed: If XMPP not enabled and no protocol provided then message will be DEBUG instead of Warning to enable XMPP.Fixed: If connect using XMPP fails with for example Connection Refused then it will be logged now and connection marked as failed for reconnection.0.2.7Fixed: Registered handlers would not be unregistered after a timeout when sending commands to HUB.Updated slixmpp from >= 1.5.2 to >= 1.7.0Updated aiohttp from >= 3.4 to 3.7.30.2.8Changed: Get remote_id from Hub without creating websocket connection0.2.9Fixed: Fixed exception in Python 3.10 by removing loop parameter (swolix)0.2.10Fixed: Fixed “module asyncio has no attribute coroutine” exception in call_raw_callback function on Python 3.11Changed: Bumped minimum required Python version to 3.9TODORedo discovery for asyncio. This will be done once XMPP is re-implemented by LogitechMore items can be done from the Harmony iOS app; determining what could be done within the library as wellIs it possible to update device configuration? |
aiohawk | No description available on PyPI. |
aiohcaptcha | aiohcaptchaAsyncIO client for the hCaptcha serviceSecure your forms using a captcha.Installpip install aiohcaptchaUsageConfigurationYou can define the secret keyHCAPTCHA_SECRET_KEYin the environment or directly pass it to theHCaptchaClientmodel as a parameter.Get the secret and public keys from thehcaptcha.com.Template<div class="h-captcha" data-sitekey="your_site_key"></div>
<script src="https://hcaptcha.com/1/api.js" async defer></script>CheckhCaptcha docsfor more details on the HTML widget.Viewfrom aiohcaptcha import HCaptchaClient
response_token = request.POST["h-captcha-response"]
client = HCaptchaClient(secret_key)
verified = await client.verify(response_token) # a booleanYou can adjust it to any Python Web framework that has async view support.If you are sending the form data using an AJAX request, use$('textarea[name=h-captcha-response]').val();for the captcha key.Response detailsResponse details are stored inclient.response,
details of theHCaptchaResponsemodel is same as the JSON response provided in the hCaptcha documentation.Extra argumentsYou can also addremote_ipandsitekey(expected key) to theclient.verifyfunction.
These parameters are explained in thehCaptcha docs.For unit testing, you can create the ClientHCaptchaClientwithdebug=Trueparameter.
In this mode, theverifyfunction will returnTrueif theuser_responsetoken andsitekeyparameters do match, otherwise it will returnFalse:client = HCaptchaClient("<SECRET_KEY>", debug=True)
assert await client.verify("<USER_TOKEN>", sitekey="<SAME_TOKEN>")
assert await client.verify("<USER_TOKEN>", sitekey="<DIFFERENT_TOKEN>") is False© 2020 Emin Mastizada. MIT Licenced. |
aiohdfs | Asyncio Python wrapper for the Hadoop WebHDFS REST API |
aiohealthcheck | aiohealthcheckThis tiny module provides a simple TCP endpoint, suitable for a healthcheck
in your microservice application. All it provides is a simple TCP endpoint
on a port to allow a container orchestration service to connect to, to
verify that the application is up.DemoPretty much just start up a long-lived task with the providedtcp_health_endpoint()coroutine function:loop.create_task(aiohealthcheck.tcp_health_endpoint(port=5000))The internal TCP server will be shut down when the task is cancelled, e.g.,
during your app’s shutdown sequence.Kubernetes Example Configurationports:
- name: liveness-port
containerPort: 5000
livenessProbe:
tcpSocket:
port: liveness-port
initialDelaySeconds: 15
periodSeconds: 20 |
aiohec | No description available on PyPI. |
aioHelloWorld | Asynchronous module for printing your dream programmeHello Worldin Python.Installingpip install aioHelloWorldExampleimport aioHelloWorld
import asyncio
async def main():
await aioHelloWorld.say()
if __name__ == "__main__":
asyncio.get_event_loop().run_until_complete(main())GithubYou can view the source codehereSupportYou can find me ondiscordThank You :) |
aiohelpersms | QuickstartInstall packagepip install aiohelpersmsInstall dependenciespip install -r aiohelpersms/requirements.txtSee examplesRead thedocumentationUsagefrom aiohelpersms import AioHelperSMS, BadApiKeyProvidedExceptionclient = AioHelperSMS('your_api_token')See examplebalance=awaitclient.get_balance()print(balance)countries=awaitclient.get_countries()print(countries)Exception handlingfromaiohelpersmsimportAioHelperSMS,BadApiKeyProvidedExceptionclient=AioHelperSMS(token)try:balance=awaitclient.get_balance()print(balance)exceptBadApiKeyProvidedExceptionase:print(e)> {'detail': 'Bad API key provided'}See the documentation for exceptions in theexceptions.mdfileSync versionfromaiohelpersmsimportHelperSMS,BadApiKeyProvidedExceptiontoken='your_api_token'defmain(token):client=HelperSMS(token)try:balance=client.get_balance()print(balance)countries=client.get_countries()print(countries)exceptBadApiKeyProvidedExceptionase:print(e)if__name__=='__main__':main()OtherLicenseProject AioHelperSMS is distributed under the MIT license |
aiohelvar | aiohelvarAsynchronous Python library to interact with Helvar Routers.This library was originally written to support the (work in progress) Helvar Home Assistant integration.Features:Manages the async TCP comms well, keeps the connection alive and listens to broadcast messagesDecodes the HelvarNet messages and translates things into Python objects that can easily be further translated into Home Assistant objectsDiscovers and retrieves Devices, Groups & Scenes and and all their properties, state and values.Keeps track of device states as scenes and devices change based on notifications from the router.Calls the more useful commands to control or read status from the above.Very much a work in progress. Known TODOS:Cluster support - we assume cluster 0 at the momentSensor supportSupport relative changes to scene levels update commandsBetter test coverage(Some of the) Known limitationsLack of unique device IDsI can't find a way to grab a unique ID for devices on the various Router busses.The DALI standard requires every device have a GTIN and a unique serial number. These appear in Helvar's router management software, but are not available on the 3rd party APIs. I've tried probing for undocumented commands with no luck.For now, I'm using the workgroup name + the helvar bus address as a unique address. This isnotunique per physical device - it is, however, unique at any point in time.Open to better suggestions!Routers don't notify changes to individual devices.We receive notifications when group scenes change, and since we know device levels for every scene, we can update devices levels without polling devices.However, we don't get notified when individual devices change their load. This shouldn't be an issue for most setups, as Helvar is scene oriented, and almost every happens that way.We also receive notifications when there are relative changes to scene levels, but we don't currently support those commands.If you're having trouble here, I suggest we implement a device polling option that can be enabled.Router doesn't report decimal scene levelsIf you set scene levels to a decimal, rather than an int. (e.g. 0.2 or 54.6). The only command available to retrieve scene levels only
returns the integer.The only time this is really a problem on dim scenes where a value of 0.25 would show light, but the command is reporting off.We get round this by polling all devices manually if we think they've been updated by a scene. Don't like it.Colour changing loads.I don't have a router that supports these as native DALI devices. So I have no idea how they appear :)The HelvarNET docs don't mention how it's supported.Requests to Helvar :)Please provide a command to retrieve a device's GTIN and / or serial number.Please provide a command to retrieve full decimal values of a scene table.DisclaimerHalvar (TM) is a registered trademark of Helvar Ltd.This software is not officially endorsed by Helvar Ltd in any way.The authors of this software provide no support, guarantees, or warranty for its use, features, safety, or suitability for any task. We do not recommend you use it for anything at all, and we don't accept any liability for any damages that may result from its use.This software is licensed under the Apache License 2.0. See the LICENCE file for more details. |
aioheos | # aioheosAn asynchronous lib for Denon Heos |
aiohere | aiohereAsynchronous Python client for the HERE APIBased onherepyInstallationpipinstallaiohereUsagefromaiohereimportAioHere,WeatherProductTypeimportasyncioAPI_KEY=""asyncdefmain():"""Show example how to get weather forecast for your location."""asyncwithAioHere(api_key=API_KEY)asaiohere:response=awaitaiohere.weather_for_coordinates(latitude=49.9836187,longitude=8.2329145,products=[WeatherProductType.FORECAST_7DAYS_SIMPLE],)lowTemperature=response["dailyForecasts"][0]["forecasts"][0]["lowTemperature"]highTemperature=response["dailyForecasts"][0]["forecasts"][0]["highTemperature"]weekday=response["dailyForecasts"][0]["forecasts"][0]["weekday"]print(f"Temperature on{weekday}will be between{lowTemperature}°C and{highTemperature}°C")if__name__=="__main__":loop=asyncio.new_event_loop()loop.run_until_complete(main()) |
aioherepy | aioherepyAsynchronous Python library that provides a simple interface to the HERE APIs. |
aioheroku3 | No description available on PyPI. |
aiohglib | aiohglibThe aiohglib is an asynchronous variant ofhglib, which is library with a fast, convenient interface to Mercurial. It uses Mercurial's command server for communication with hg.The code itself takes advantage of asyncio library and async/await syntax.Another difference against standard hglib is suport for timezones and changesets details like p1, p2 and extras.Basic usageimportasyncioimportaiohglibasyncdefmain():asyncwithaiohglib.open(path)asclient:log=awaitclient.log(revrange="tip")print(log)# Depending on your Python version you need to run one of those:# Python 3.7 or newerasyncio.run(main())# Python 3.6loop=asyncio.get_event_loop()loop.run_until_complete(main())loop.close()# Python 3.6 on Windowsloop=asyncio.ProactorEventLoop()loop.run_until_complete(main())loop.close()DependenciesPython 3.6pytzchardet(optional)Changelog1.5Changed string decoding and codec detection to be more safe.1.4Fixed await syntax in client.pyFixed redundant __bool__ in util.pyOptional detection of encoding for changeset's author and description via chardet moduleOptional safe_template is nownotused by defaultLicenceMITContactMichal Šiš[email protected] |
aiohipchat | UNKNOWN |
aiohivebot | An async python library for writing bots and DApp backends for the HIVE blockchain |
aiohomeconnect | aiohomeconnectDocumentation:https://aiohomeconnect.readthedocs.ioSource Code:https://github.com/MartinHjelmare/aiohomeconnectAn asyncio client for the Home Connect API.InstallationInstall this via pip (or your favourite package manager):pip install aiohomeconnectCreditsThis package was created withCopierand thebrowniebroke/pypackage-templateproject template. |
aiohomekit | aiohomekitThis library implements the HomeKit protocol for controlling Homekit accessories using asyncio.It's primary use is for with Home Assistant. We target the same versions of python as them and try to follow their code standards.At the moment we don't offer any API guarantees. API stability and documentation will happen after we are happy with how things are working within Home Assistant.Contributingaiohomekitis primarily for use with Home Assistant. Lots of users are using it with devices from a wide array of vendors. As a community open source project we do not have the hardware or time resources to certify every device with multiple vendors projects. We may be conservative about larger changes or changes that are low level. We do ask where possible that any changes should be tested with a certified HomeKit implementations of shipping products, not just against emulators or other uncertified implementations.Because API breaking changes would hamper our ability to quickly update Home Assistant to the latest code, if you can please submit a PR to updatehomekit_controllertoo. If they don't your PR maybe on hold until someone is available to write such a PR.Please bear in mind that some shipping devices interpret the HAP specification loosely. In general we prefer to match the behaviour of real HAP controllers even where their behaviour is not strictly specified. Here are just some of the kinds of problems we've had to work around:Despite the precise formatting of JSON being unspecified, there are devices in the wild that cannot handle spaces when parsing JSON. For example,{"foo": "bar"}vs{"foo":"bar"}. This means we never use a "pretty" encoding of JSON.Despite a boolean being explicitly defined as0,1,trueorfalsein the spec, some devices only support 3 of the 4. This means booleans must be encoded as0or1.Some devices have shown themselves to be sensitive to headers being missing, in the wrong order or if there are extra headers. So we ensure that only the headers iOS sends are present, and that the casing and ordering is the same.Some devices are sensitive to a HTTP message being split into separate TCP packets. So we take care to only write a full message to the network stack.And so on. As a rule we need to be strict about what we send and loose about what we receive.Device compatibilityaiohomekitis primarily tested via Home Assistant with a Phillips Hue bridge and an Eve Extend bridge. It is known to work to some extent with many more devices though these are not currently explicitly documented anywhere at the moment.You can look at the problems your device has faced in the home-assistantissues list.FAQHow do I use this?It's published on pypi asaiohomekitbut its still under early development - proceed with caution.The main consumer of the API is thehomekit_controllerin Home Assistant so that's the best place to get a sense of the API.Does this support BLE accessories?No. Eventually we hope to viaaioblewhich provides an asyncio bluetooth abstraction that works on Linux, macOS and Windows.Can i use this to make a homekit accessory?No, this is just the client part. You should use one the of other implementations:homekit_python(this is used a lot during aiohomekit development)HAP-pythonWhy doesn't Home Assistant use library X instead?At the time of writing this is the only python 3.7/3.8 asyncio HAP client with events support.Why doesn't aiohomekit use library X instead?Where possible aiohomekit uses libraries that are easy to install with pip, are ready available as wheels (including on Raspberry Pi via piwheels), are cross platform (including Windows) and are already used by Home Assistant. They should not introduce hard dependencies on uncommon system libraries. The intention here is to avoid any difficulty in the Home Assistant build process.People are often alarmed at the hand rolled HTTP code and suggest using an existing HTTP library likeaiohttp. High level HTTP libraries are pretty much a non-starter because:Of the difficulty of adding in HAP session security without monkey patches.They don't expect responses without requests (i.e. events).As mentioned above, some of these devices are very sensitive. We don't care if your change is compliant with every spec if it still makes a real world device cry. We are not in a position to demand these devices be fixed. So instead we strive for byte-for-byte accuracy on our write path. Any library would need to give us that flexibility.Some parts of the responses are actually not HTTP, even though they look it.We are also just reluctant to make a change that large for something that is working with a lot of devices. There is a big chance of introducing a regression.Of course a working proof of concept (using a popular well maintained library) that has been tested with something like a Tado internet bridge (including events) would be interesting.ThanksThis library wouldn't have been possible without homekit_python, a synchronous implementation of both the client and server parts of HAP. |
aiohood | No description available on PyPI. |
aiohook | aiohook – simple plugins for asyncio, trio and curioaiohooksis a small library meant to help implementing a plugin system in
Python 3.7+ asynchronous applications developed with ananyio-compatible
library. It can also be used to set up synchronous function hooks.QuickstartDeclare the signature of the hook coroutine by decorating a dummydeforasync def(without implementation, or with a default one) withaiohook.spec.awaitthe dummy coroutine where you would want the plugin one to be called.Implement the dummy coros in a separate module or class and decorate them withaiohook.impl('reference.to.dummy').Callaiohook.register(reference)to register the decorated implementations
inreference(object instance or module).Non-implemented hooks result in the default implementation being called.Registering multiple implementations of the same hook raises an exception.Basic usageIn this story, your name is Wallace, you are implementing an awesome async
application accepting plugins. Your user, Gromit, wants to make use of your
plugin system to inject his custom parsing logic.Application designerYou must first define the signature of each hook function, for
instance in a separatepluginspecs.pyfile:fromtypingimportAsyncIterator,[email protected](sentence:str)->AsyncIterator[str]:# Describe the purpose of the hook, arguments etc in the docstring"""Split string of characters into individual tokens."""# workaround for python's type system inability to declare a generator# function without a body with a 'yield' [email protected]_token(word:str)->Optional[str]:"""Preprocess each raw token, for instance as a normalization step."""In your application code, you then call your spec'ed out functions as if they
had already been implemented:importsys,asyncio,importlib,aiohookfrompluginspecsimporttokenize,transform_tokenasyncdefmain():withopen(sys.argv[1],'r')asf:source=f.read()asyncfortokenintokenize(source):transformed=awaittransform_token(token)print(transformed,end='')if__name__=='__main__':aiohook.register(importlib.import_module(sys.argv[1]))asyncio.run(main())Plugin developerGromit wants to use Wallace's application to transform text files. He creates a
pip-installable module in which thegromify.pyfile looks as follows:importasyncio,aiohook,randomfromtypingimportAsyncIterator,[email protected]('pluginspecs.tokenize')asyncdefgive_word(text:str)->AsyncIterator[str]:forwintext.split():[email protected]('pluginspecs.transform_token')asyncdefbark_and_pause(word:str)->Optional[str]:awaitasyncio.sleep(random.uniform(0,2))return'woo'+'o'*(max(len(word)-2,0))+'f'Gromit pip-installs his plugin and Wallace's text processing app, and then calls
the latter, providing as first argument the absolute import path to the gromify
module.Note that I haven't actually tried the above example, and also that it makes
little sense to use async functions in this case, but I think it illustrates the
basic usage os aiohook nicely.For less silly examples, please refer to the sample applications used as
functional tests intests/functionalDevelopmentTwo requirements files are used to describe the development setup:The requirements.txt file describes a working development environment with all
pinned dependencies.The requirements-base.txt file contains the direct unpinned dependencies only
necessary for a full development environment.Step-by-step guide to set up a development environmentThis assumes thatpyenvand pyenv-virtualenv
are installed, and the OS is somehow Unix-like. Commands are executed from the
root of the repo.pyenvinstall3.7.4
pyenvvirtualenv3.7.4aiohook-dev-3.7.4pyenvactivateaiohook-dev-3.7.4To work on the main library, it is best to just pip install it as an editable
package, and install the rest of the dev requirements:pipinstall-e.
pipinstall-rrequirements.txtTo work on one of the functional test applications under
[tests/functional(tests/functional), it is useful to also install it in editable
mode in the same environment:pipinstall-etests/functional/text_processing_app# Try it outprocess_texttextproc_pluginrequirements.txtrequirements-transformed.txtTesting with coveragepytest--cov=aiohooktests/ |
aiohopcolony | Asyncio HopColony SDK to communicate with backend for Python developers |
aiohoripy | This is a asynchronous wrapper for Hori-API namedaiohoripyThe way you use it it's so simple:importaiohoripy# orfromaiohoripyimportsfw,nsfwimportdiscordfromdiscord.extimportcommandsbot=commands.Bot(command_prefix="prefix",intents=discord.Intents.all())@bot.eventasyncdefon_ready():print("I'm ready")@bot.command()asyncdefwaifu(ctx):image=awaitsfw(tag="waifu")# orimage=awaitnsfw(tag="waifu")awaitctx.send(image)bot.run("TOKEN")The tags are the same as the tags that the api givessfw tags are:["all", "husbando", "waifu"]nsfw tags are:["ass", "ecchi", "ero", "hentai", "maid", "milf", "oppai", "oral", "paizuri", "selfies", "uniform"]The output thatimage`` gives is the same as the json results in the APIand you can get them with:image["code", "is_over18", "tag_id", "tag_name", "file", "url"]Made by lvlahraam#8435 |
aio-hs2 | UNKNOWN |
aiohttp | Key FeaturesSupports both client and server side of HTTP protocol.Supports both client and server Web-Sockets out-of-the-box and avoids
Callback Hell.Provides Web-server with middleware and pluggable routing.Getting startedClientTo get something from the web:importaiohttpimportasyncioasyncdefmain():asyncwithaiohttp.ClientSession()assession:asyncwithsession.get('http://python.org')asresponse:print("Status:",response.status)print("Content-type:",response.headers['content-type'])html=awaitresponse.text()print("Body:",html[:15],"...")asyncio.run(main())This prints:Status: 200
Content-type: text/html; charset=utf-8
Body: <!doctype html> ...Coming fromrequests? Readwhy we need so many lines.ServerAn example using a simple server:# examples/server_simple.pyfromaiohttpimportwebasyncdefhandle(request):name=request.match_info.get('name',"Anonymous")text="Hello, "+namereturnweb.Response(text=text)asyncdefwshandle(request):ws=web.WebSocketResponse()awaitws.prepare(request)asyncformsginws:ifmsg.type==web.WSMsgType.text:awaitws.send_str("Hello,{}".format(msg.data))elifmsg.type==web.WSMsgType.binary:awaitws.send_bytes(msg.data)elifmsg.type==web.WSMsgType.close:breakreturnwsapp=web.Application()app.add_routes([web.get('/',handle),web.get('/echo',wshandle),web.get('/{name}',handle)])if__name__=='__main__':web.run_app(app)Documentationhttps://aiohttp.readthedocs.io/Demoshttps://github.com/aio-libs/aiohttp-demosExternal linksThird party librariesBuilt with aiohttpPowered by aiohttpFeel free to make a Pull Request for adding your link to these pages!Communication channelsaio-libs Discussions:https://github.com/aio-libs/aiohttp/discussionsgitter chathttps://gitter.im/aio-libs/LobbyWe supportStack Overflow.
Please addaiohttptag to your question there.Requirementsasync-timeoutattrsmultidictyarlfrozenlistOptionally you may install theaiodnslibrary (highly recommended for sake of speed).Licenseaiohttpis offered under the Apache 2 license.KeepsafeThe aiohttp community would like to thank Keepsafe
(https://www.getkeepsafe.com) for its support in the early days of
the project.Source codeThe latest developer version is available in a GitHub repository:https://github.com/aio-libs/aiohttpBenchmarksIf you are interested in efficiency, the AsyncIO community maintains a
list of benchmarks on the official wiki:https://github.com/python/asyncio/wiki/Benchmarks |
aio.http | This package has been moved toaio.http.server(pypi) |
aiohttp_ac_hipchat | A Python 3 [aiohttp](aiohttp.readthedocs.org)-based library for building [HipChat Connect add-ons](https://www.hipchat.com/docs/apiv2/addons). This is an early, alpha-quality release,
but can be used to build real add-ons today. Future versions may include backward-incompatible changes.RequirementsPython >= 3.3asynciohttps://pypi.python.org/pypi/asyncioLicenseaiohttp_ac_hipchatis offered under the Apache 2 license.Source codeThe latest developer version is available in a BitBucket repository:https://bitbucket.org/atlassianlabs/aiohttp_ac_hipchat |
aiohttp_ac_hipchat_postgre | aiohttp_ac_hipchat_postgre==================A Python 3 [aiohttp](http://aiohttp.readthedocs.org) -based library for using PostgreSQL stores with [aiohttp_ac_hipchat](http://bitbucket.org/atlassianlabs/aiohttp_ac_hipchat). This is an early, alpha-quality release,but can be used to build real add-ons today. Future versions may include backward-incompatible changes.Requirements------------- Python >= 3.3- asyncio https://pypi.python.org/pypi/asyncio- aiopg https://github.com/aio-libs/aiopgLicense-------``aiohttp_ac_hipchat_postgre`` is offered under the Apache 2 license.Source code-----------The latest developer version is available in a BitBucket repository:https://bitbucket.org/ramiroberrelleza/aiohttp_ac_hipchat_postgre |
aiohttp-admin | aiohttp_adminaiohttp_adminwill help you on building an admin interface
on top of an existing data model. Library designed to be database agnostic and
decoupled of any ORM or database layer. Admin module relies on async/await syntax (PEP492)
thusnotcompatible with Python older than 3.5.Designaiohttp_adminusing following design philosophy:backend and frontend of admin views are decoupled by REST API as a
result it is possible to change admin views without changing anypythoncode. On browser side user interacts with single page application (ng-admin).admin views are database agnostic, if it is possible to implement REST API
it should be straightforward to add admin views. Some filtering features may
be disabled if database do not support some kind of filtering.Supported backendsPostgreSQL with,aiopgandsqlalchemy.coreMySQL withaiomysqlandsqlalchemy.coreMongodb withmotorMailing Listhttps://groups.google.com/forum/#!forum/aio-libsRequirementsPython3.5+aiopgoraiomysqlormotorCHANGESxx |
aiohttp-admin2 | Aiohttp adminDemo site|Demo source code.The aiohttp admin is a library for build admin interface for applications based
on the aiohttp. With this library you can ease to generate CRUD views for your
data (for data storages which support by aiohttp admin) and flexibly customize
representation and access to these.Free software: MIT licenseDocumentation:https://aiohttp-admin2.readthedocs.io.InstallationThe first step which you need to do it’s installing librarypipinstallaiohttp_admin2History0.1.0 (2020-04-28)First release on PyPI. |
aiohttp-aiocache | aiohttp-aiocacheCaching middleware foraiohttpserver
withaiocacheunder the hood.
Inspired byaiohttp-cache.Installationpipinstallaiohttp-aiocacheorpoetryaddaiohttp-aiocacheOptionalaiocachedependencies for redis, memcached and msgpack support
will not be installed. Install them manually if required.Usageimportasyncioimportaiohttp.webaswebfromaiocacheimportCachefromaiocache.serializersimportPickleSerializerfromaiohttp_aiocacheimportcached,register_cache@cached# mark handler with decoratorasyncdefhandler(_:web.Request)->web.Response:awaitasyncio.sleep(1)returnweb.Response(text="Hello world")app=web.Application()app.router.add_route("GET","/",handler)# create aiocache instancecache=Cache(Cache.MEMORY,serializer=PickleSerializer(),namespace="main",ttl=60,)# register cache backend in appplicationregister_cache(app,cache)web.run_app(app)LimitationsSupport caching for GET requests only.LicenseMIT |
aiohttp-aiopylimit | No description available on PyPI. |
aiohttpapi | aiohttpapipip install aiohttpapiContributingContributing |
aiohttp-api-client | aiohttp-api-clientRequires: python 3.6+, aiohttp.Example:importaiohttpfromaiohttp_api_client.json_apiimport\JsonApiClient,JsonApiRequest,JsonApiError,JsonApiDetailsasyncdefrun(http_client:aiohttp.ClientSession):api_client=JsonApiClient(http_client)response=awaitapi_client(JsonApiRequest('GET','https://example.com/api/'))assertresponse.json=={'ok':True}try:awaitapi_client(JsonApiRequest('GET','https://example.com/api/bad-request/'))exceptJsonApiErrorase:asserte.details==JsonApiDetails(http_status=400,http_reason='Bad Request',content_type='application/json',bytes=b'{"ok": false}',text='{"ok": false}',)else:assertFalse |
aiohttp-apiset | Package to build routes and validate request using swagger specification 2.0.FeaturesBuilding of the routing from specification swaggerUsing inclusions other specifications with concatenate urlOptional output of the resulting specification and view embedswagger-uiAdvanced router with TreeResourceExtract specify parameters from request and validate with jsonschemaSerialize data as response with middlewareUsecasePackage aiohttp_apiset allows supports several strategies:The foreign specification. When the specification
is made and maintained by another team.The specification in the code. When the fragments of specification
are placed in the docstrings.Mixed strategy. When routing are located in the specification files
and operations are described in the docstrings.Exampleasyncdefhandler(request,pet_id):"""
---
tags: [Pet]
description: Info about pet
parameters:
- name: pet_id
in: path
type: integer
minimum: 0
responses:
200:
description: OK
400:
description: Validation error
404:
description: Not found
"""pet=awaitdb.pets.find(pet_id)ifnotpet:return{'status':404,'msg':'Not Found'}return{'pet':pet,# dict serialized inside jsonify}defmain():router=SwaggerRouter(swagger_ui='/swagger/',version_ui=2,)router.add_get('/pets/{pet_id}',handler=handler)app=web.Application(router=router,middlewares=[jsonify],)web.run_app(app)Is now available in the swagger-ui to the addresshttp://localhost:8080/swagger/.
Available both branch swagger-ui. For use branch 3.x visithttp://localhost:8080/swagger/?version=3Examples:examplesDevelopmentCheck code:hatchrunlint:allFormat code:hatchrunlint:fmtRun tests:hatchrunpytestRun tests with coverage:hatchruncov |
aiohttp-apispec | aiohttp-apispecBuild and document REST APIs withaiohttpandapispecaiohttp-apispeckey features:docsandrequest_schemadecorators
to add swagger spec support out of the box;validation_middlewaremiddleware to enable validating
with marshmallow schemas from those decorators;SwaggerUIsupport.New from version 2.0-match_info_schema,querystring_schema,form_schema,json_schema,headers_schemaandcookies_schemadecorators for specific request parts validation.
Lookherefor more info.aiohttp-apispecapi is fully inspired byflask-apispeclibraryContentsInstallQuickstartAdding validation middlewareMore decoratorsCustom error handlingBuild swagger web clientVersioningInstallpip install aiohttp-apispecQuickstartAlso you can readblog postabout quickstart with aiohttp-apispecfromaiohttp_apispecimport(docs,request_schema,setup_aiohttp_apispec,)fromaiohttpimportwebfrommarshmallowimportSchema,fieldsclassRequestSchema(Schema):id=fields.Int()name=fields.Str(description="name")@docs(tags=["mytag"],summary="Test method summary",description="Test method description",)@request_schema(RequestSchema(strict=True))asyncdefindex(request):returnweb.json_response({"msg":"done","data":{}})app=web.Application()app.router.add_post("/v1/test",index)# init docs with all parameters, usual for ApiSpecsetup_aiohttp_apispec(app=app,title="My Documentation",version="v1",url="/api/docs/swagger.json",swagger_path="/api/docs",)# Now we can find spec on 'http://localhost:8080/api/docs/swagger.json'# and docs on 'http://localhost:8080/api/docs'web.run_app(app)Class based views are also supported:classTheView(web.View):@docs(tags=["mytag"],summary="View method summary",description="View method description",)@request_schema(RequestSchema(strict=True))@response_schema(ResponseSchema(),200)defdelete(self):returnweb.json_response({"msg":"done","data":{"name":self.request["data"]["name"]}})app.router.add_view("/v1/view",TheView)As alternative you can add responses info todocsdecorator, which is more compact way.
And it allows you not to use schemas for responses documentation:@docs(tags=["mytag"],summary="Test method summary",description="Test method description",responses={200:{"schema":ResponseSchema,"description":"Success response",},# regular response404:{"description":"Not found"},# responses without schema422:{"description":"Validation error"},},)@request_schema(RequestSchema(strict=True))asyncdefindex(request):returnweb.json_response({"msg":"done","data":{}})Adding validation middlewarefromaiohttp_apispecimportvalidation_middleware...app.middlewares.append(validation_middleware)Now you can access all validated data in route fromrequest['data']like so:@docs(tags=["mytag"],summary="Test method summary",description="Test method description",)@request_schema(RequestSchema(strict=True))@response_schema(ResponseSchema,200)asyncdefindex(request):uid=request["data"]["id"]name=request["data"]["name"]returnweb.json_response({"msg":"done","data":{"info":f"name -{name}, id -{uid}"}})You can changeRequest's'data'param to another withrequest_data_nameargument ofsetup_aiohttp_apispecfunction:setup_aiohttp_apispec(app=app,request_data_name="validated_data",)...@request_schema(RequestSchema(strict=True))asyncdefindex(request):uid=request["validated_data"]["id"]...Also you can do it for specific view usingput_intoparameter (beginning from version 2.0):@request_schema(RequestSchema(strict=True),put_into="validated_data")asyncdefindex(request):uid=request["validated_data"]["id"]...More decoratorsStarting from version 2.0 you can use shortenings for documenting and validating
specific request parts like cookies, headers etc using those decorators:Decorator nameDefault put_into parammatch_info_schemamatch_infoquerystring_schemaquerystringform_schemaformjson_schemajsonheaders_schemaheaderscookies_schemacookiesAnd example:@docs(tags=["users"],summary="Create new user",description="Add new user to our toy database",responses={200:{"description":"Ok. User created","schema":OkResponse},401:{"description":"Unauthorized"},422:{"description":"Validation error"},500:{"description":"Server error"},},)@headers_schema(AuthHeaders)# <- schema for headers validation@json_schema(UserMeta)# <- schema for json body validation@querystring_schema(UserParams)# <- schema for querystring params validationasyncdefcreate_user(request:web.Request):headers=request["headers"]# <- validated headers!json_data=request["json"]# <- validated json!query_params=request["querystring"]# <- validated querystring!...Custom error handlingIf you want to catch validation errors by yourself you
could useerror_callbackparameter and create your custom error handler. Note that
it can be one of coroutine or callable and it should
have interface exactly like in examples below:frommarshmallowimportValidationError,SchemafromaiohttpimportwebfromtypingimportOptional,Mapping,NoReturndefmy_error_handler(error:ValidationError,req:web.Request,schema:Schema,error_status_code:Optional[int]=None,error_headers:Optional[Mapping[str,str]]=None,)->NoReturn:raiseweb.HTTPBadRequest(body=json.dumps(error.messages),headers=error_headers,content_type="application/json",)setup_aiohttp_apispec(app,error_callback=my_error_handler)Also you can create your own exceptions and create
regular Request in middleware like so:classMyException(Exception):def__init__(self,message):self.message=message# It can be coroutine as well:asyncdefmy_error_handler(error,req,schema,error_status_code,error_headers):awaitreq.app["db"].do_smth()# So you can use some async stuffraiseMyException({"errors":error.messages,"text":"Oops"})# This middleware will handle your own exceptions:@web.middlewareasyncdefintercept_error(request,handler):try:returnawaithandler(request)exceptMyExceptionase:returnweb.json_response(e.message,status=400)setup_aiohttp_apispec(app,error_callback=my_error_handler)# Do not forget to add your own middleware before validation_middlewareapp.middlewares.extend([intercept_error,validation_middleware])Build swagger web client3.X SwaggerUI versionJust addswagger_pathparameter tosetup_aiohttp_apispecfunction.For example:setup_aiohttp_apispec(app,swagger_path="/docs")Then go to/docsand see awesome SwaggerUI2.X SwaggerUI versionIf you prefer older version you can useaiohttp_swaggerlibrary.aiohttp-apispecaddsswagger_dictparameter to aiohttp web application
after initialization (withsetup_aiohttp_apispecfunction).
So you can use it easily like:fromaiohttp_apispecimportsetup_aiohttp_apispecfromaiohttp_swaggerimportsetup_swaggerdefcreate_app(app):setup_aiohttp_apispec(app)asyncdefswagger(app):setup_swagger(app=app,swagger_url="/api/doc",swagger_info=app["swagger_dict"])app.on_startup.append(swagger)# now we can access swagger client on '/api/doc' url...returnappVersioningThis software followsSemantic Versioning.Please star this repository if this project helped you! |
aiohttp-apispec-patch | aiohttp-apispecBuild and document REST APIs withaiohttpandapispecaiohttp-apispeckey features:docsandrequest_schemadecorators
to add swagger spec support out of the box;validation_middlewaremiddleware to enable validating
with marshmallow schemas from those decorators;SwaggerUIsupport.New from version 2.0-match_info_schema,querystring_schema,form_schema,json_schema,headers_schemaandcookies_schemadecorators for specific request parts validation.
Lookherefor more info.aiohttp-apispecapi is fully inspired byflask-apispeclibraryContentsInstallQuickstartAdding validation middlewareMore decoratorsCustom error handlingBuild swagger web clientInstallpip install aiohttp-apispecQuickstartfromaiohttp_apispecimport(docs,request_schema,setup_aiohttp_apispec,)fromaiohttpimportwebfrommarshmallowimportSchema,fieldsclassRequestSchema(Schema):id=fields.Int()name=fields.Str(description="name")@docs(tags=["mytag"],summary="Test method summary",description="Test method description",)@request_schema(RequestSchema(strict=True))asyncdefindex(request):returnweb.json_response({"msg":"done","data":{}})app=web.Application()app.router.add_post("/v1/test",index)# init docs with all parameters, usual for ApiSpecsetup_aiohttp_apispec(app=app,title="My Documentation",version="v1",url="/api/docs/swagger.json",swagger_path="/api/docs",)# Now we can find spec on 'http://localhost:8080/api/docs/swagger.json'# and docs on 'http://localhost:8080/api/docs'web.run_app(app)Class based views are also supported:classTheView(web.View):@docs(tags=["mytag"],summary="View method summary",description="View method description",)@request_schema(RequestSchema(strict=True))@response_schema(ResponseSchema(),200)defdelete(self):returnweb.json_response({"msg":"done","data":{"name":self.request["data"]["name"]}})app.router.add_view("/v1/view",TheView)As alternative you can add responses info todocsdecorator, which is more compact way.
And it allows you not to use schemas for responses documentation:@docs(tags=["mytag"],summary="Test method summary",description="Test method description",responses={200:{"schema":ResponseSchema,"description":"Success response",},# regular response404:{"description":"Not found"},# responses without schema422:{"description":"Validation error"},},)@request_schema(RequestSchema(strict=True))asyncdefindex(request):returnweb.json_response({"msg":"done","data":{}})Adding validation middlewarefromaiohttp_apispecimportvalidation_middleware...app.middlewares.append(validation_middleware)Now you can access all validated data in route fromrequest['data']like so:@docs(tags=["mytag"],summary="Test method summary",description="Test method description",)@request_schema(RequestSchema(strict=True))@response_schema(ResponseSchema,200)asyncdefindex(request):uid=request["data"]["id"]name=request["data"]["name"]returnweb.json_response({"msg":"done","data":{"info":f"name -{name}, id -{uid}"}})You can changeRequest's'data'param to another withrequest_data_nameargument ofsetup_aiohttp_apispecfunction:setup_aiohttp_apispec(app=app,request_data_name="validated_data",)...@request_schema(RequestSchema(strict=True))asyncdefindex(request):uid=request["validated_data"]["id"]...Also you can do it for specific view usingput_intoparameter (beginning from version 2.0):@request_schema(RequestSchema(strict=True),put_into="validated_data")asyncdefindex(request):uid=request["validated_data"]["id"]...More decoratorsStarting from version 2.0 you can use shortenings for documenting and validating
specific request parts like cookies, headers etc using those decorators:Decorator nameDefault put_into parammatch_info_schemamatch_infoquerystring_schemaquerystringform_schemaformjson_schemajsonheaders_schemaheaderscookies_schemacookiesAnd example:@docs(tags=["users"],summary="Create new user",description="Add new user to our toy database",responses={200:{"description":"Ok. User created","schema":OkResponse},401:{"description":"Unauthorized"},422:{"description":"Validation error"},500:{"description":"Server error"},},)@headers_schema(AuthHeaders)# <- schema for headers validation@json_schema(UserMeta)# <- schema for json body validation@querystring_schema(UserParams)# <- schema for querystring params validationasyncdefcreate_user(request:web.Request):headers=request["headers"]# <- validated headers!json_data=request["json"]# <- validated json!query_params=request["querystring"]# <- validated querystring!...Custom error handlingIf you want to catch validation errors by yourself you
could useerror_callbackparameter and create your custom error handler. Note that
it can be one of coroutine or callable and it should
have interface exactly like in examples below:frommarshmallowimportValidationError,SchemafromaiohttpimportwebfromtypingimportOptional,Mapping,NoReturndefmy_error_handler(error:ValidationError,req:web.Request,schema:Schema,error_status_code:Optional[int]=None,error_headers:Optional[Mapping[str,str]]=None,)->NoReturn:raiseweb.HTTPBadRequest(body=json.dumps(error.messages),headers=error_headers,content_type="application/json",)setup_aiohttp_apispec(app,error_callback=my_error_handler)Also you can create your own exceptions and create
regular Request in middleware like so:classMyException(Exception):def__init__(self,message):self.message=message# It can be coroutine as well:asyncdefmy_error_handler(error,req,schema,error_status_code,error_headers):awaitreq.app["db"].do_smth()# So you can use some async stuffraiseMyException({"errors":error.messages,"text":"Oops"})# This middleware will handle your own exceptions:@web.middlewareasyncdefintercept_error(request,handler):try:returnawaithandler(request)exceptMyExceptionase:returnweb.json_response(e.message,status=400)setup_aiohttp_apispec(app,error_callback=my_error_handler)# Do not forget to add your own middleware before validation_middlewareapp.middlewares.extend([intercept_error,validation_middleware])Build swagger web client3.X SwaggerUI versionJust addswagger_pathparameter tosetup_aiohttp_apispecfunction.For example:setup_aiohttp_apispec(app,swagger_path="/docs")Then go to/docsand see awesome SwaggerUI2.X SwaggerUI versionIf you prefer older version you can useaiohttp_swaggerlibrary.aiohttp-apispecaddsswagger_dictparameter to aiohttp web application
after initialization (withsetup_aiohttp_apispecfunction).
So you can use it easily like:fromaiohttp_apispecimportsetup_aiohttp_apispecfromaiohttp_swaggerimportsetup_swaggerdefcreate_app(app):setup_aiohttp_apispec(app)asyncdefswagger(app):setup_swagger(app=app,swagger_url="/api/doc",swagger_info=app["swagger_dict"])app.on_startup.append(swagger)# now we can access swagger client on '/api/doc' url...returnappPlease star this repository if this project helped you! |
aiohttp-apispec-plugin | aiohttp-apispec-pluginLightweightapispecplugin that generates OpenAPI specification foraiohttpweb applications.Installationpipinstallaiohttp-apispec-pluginExamplesWith class based viewfromaiohttpimportwebfromaiohttp_apispec_pluginimportAioHttpPluginfromapispecimportAPISpecclassUserView(web.View):asyncdefget(self)->web.Response:"""User Detail View---summary: Get Userdescription: Get User Data For Given `user_id`parameters:- name: user_idin: pathdescription: User IDrequired: trueschema:type: stringresponses:200:description: Successfully retrieved user detailscontent:application/json:schema:properties:id:type: integerusername:type: stringfirst_name:type: stringlast_name:type: string"""app=web.Application()app.router.add_view("/api/v1/users/{user_id}",UserView)# Create an APISpecspec=APISpec(title="AioHttp Application",version="1.0.0",openapi_version="3.0.3",plugins=[AioHttpPlugin(app),],)spec.path(resource=UserView)print(spec.to_yaml())"""info:title: AioHttp Applicationversion: 1.0.0openapi: 3.0.3paths:/api/v1/users/{user_id}:get:description: Get User Data For Given `user_id`parameters:- description: User IDin: pathname: user_idrequired: trueschema:type: stringresponses:'200':content:application/json:schema:properties:first_name:type: stringid:type: integerlast_name:type: stringusername:type: stringdescription: Successfully retrieved user detailssummary: Get User"""With function based viewfromaiohttpimportwebfromaiohttp_apispec_pluginimportAioHttpPluginfromapispecimportAPISpecasyncdefget_user(request:web.Request)->web.Response:"""User Detail View---summary: Get Userdescription: Get User Data For Given `user_id`responses:200:description: Successfully retrieved user details"""app=web.Application()app.router.add_get("/api/v1/users/{user_id}",get_user)# Create an APISpecspec=APISpec(title="AioHttp Application",version="1.0.0",openapi_version="3.0.3",plugins=[AioHttpPlugin(app),],)spec.path(resource=get_user)print(spec.to_yaml())# same behaviorWithdataclassespluginfromdataclassesimportdataclassfromaiohttpimportwebfromaiohttp_apispec_pluginimportAioHttpPluginfromapispecimportAPISpecfromdataclasses_jsonschemaimportJsonSchemaMixinfromdataclasses_jsonschema.apispecimportDataclassesPlugin@dataclassclassUser(JsonSchemaMixin):"""User Schema"""id:intusername:strasyncdefget_user(request:web.Request)->web.Response:"""User Detail View---summary: Get Userdescription: Get User Data For Given `user_id`responses:200:description: Successfully retrieved user detailscontent:application/json:schema: User"""app=web.Application()app.router.add_get("/api/v1/users/{user_id}",get_user)spec=APISpec(title="AioHttp Application",version="1.0.0",openapi_version="3.0.3",plugins=[AioHttpPlugin(app),DataclassesPlugin(),],)spec.components.schema("User",schema=User)spec.path(resource=get_user)print(spec.to_yaml())"""components:schemas:User:description: User Schemaproperties:id:type: integerusername:type: stringrequired:- id- usernametype: objectinfo:title: AioHttp Applicationversion: 1.0.0openapi: 3.0.3paths:/api/v1/users/{user_id}:get:description: Get User Data For Given `user_id`responses:'200':content:application/json:schema:$ref: '#/components/schemas/User'description: Successfully retrieved user detailssummary: Get User"""RequirementsPython >= 3.6Dependencies:aiohttpapispecPyYAMLOther libs to checkaiohttp-apispecfalcon-apispecdataclasses-jsonschema |
aiohttp-asgi | aiohttp-asgiThis module provides a way to use any ASGI compatible frameworks and aiohttp together.ExamplefromaiohttpimportwebfromfastapiimportFastAPIfromstarlette.requestsimportRequestasASGIRequestfromaiohttp_asgiimportASGIResourceasgi_app=FastAPI()@asgi_app.get("/asgi")asyncdefroot(request:ASGIRequest):return{"message":"Hello World","root_path":request.scope.get("root_path")}aiohttp_app=web.Application()# Create ASGIResource which handle# any request startswith "/asgi"asgi_resource=ASGIResource(asgi_app,root_path="/asgi")# Register resourceaiohttp_app.router.register_resource(asgi_resource)# Mount startup and shutdown events from aiohttp to ASGI appasgi_resource.lifespan_mount(aiohttp_app)# Start the applicationweb.run_app(aiohttp_app)Installationpipinstallaiohttp-asgiASGI HTTP serverCommand line tool for starting aiohttp web server with ASGI app.ExampleCreate thetest_app.pyfromstarlette.applicationsimportStarlettefromstarlette.responsesimportJSONResponsefromstarlette.routingimportRouteasyncdefhomepage(request):returnJSONResponse({'hello':'world'})routes=[Route("/",endpoint=homepage)]application=Starlette(debug=True,routes=routes)and run thetest_app.pywithaiohttp-asgiaiohttp-asgi\--address"[::1]"\--port8080\test_app:applicationalternatively usingpython -mpython-maiohttp_asgi\--address"[::1]"\--port8080\test_app:application |
aiohttp-asynctools | Automatically add session management to a classSome function and classes to help you deal with aiohttp client sessions. This is made after thisdiscussion. This works for decorating both coroutines and asynchronous generators methods.Installationpipinstallaiohttp-asynctoolsUsageAutomatically attach anaiohttp.ClientSessionobject to your class in a fast and clean way with the following 3 steps:ImportasynctoolsMake your class extendasynctools.AbstractSessionContainerDecorate asynchronous methods/generators [email protected]_sessionto attach asessionargument.Optionaly, you can also cutomize the instanciation ofAbstractSessionContainerin your__init__method.
Here is what it looks like for a simple example using amath API:importasynctools# 1.MATH_API_URL="http://api.mathjs.org/v4"classMathRequests(asynctools.AbstractSessionContainer):# [email protected]_session# 3.asyncdefget_text(self,url,params,session=None):asyncwithsession.get(url,params=params)asresponse:returnawaitresponse.text()asyncdefget_square(self,value):params={"expr":f"{value}^2"}returnawaitself.get_text(MATH_API_URL,params=params)You are now ready to instantiate aMathRequestscontext manager and start requesting the math service using a singleaiohttpsession(the session is hidden from theMathRequestsuser). Here is how you could build a math server using the new class (basically we wrote a wrapper for the Math API and now we expose our own API).fromaiohttpimportwebroutes=web.RouteTableDef()@routes.get('/squares')asyncdefsquares(request):values=request.query['values'].split(',')asyncwithMathRequests()asmaths:squares=awaitasyncio.gather(*(maths.get_square(v)forvinvalues))return{'values':values,'squares':squares,}maths_app=web.Application()maths_app.add_routes(routes)if__name__=="__main__":web.run_app(app)We are now ready to test:curl'http://localhost:8080/squares?values=1,2,3,4,5,6,7,8,9,10'Which should output:{"values":["1","2","3","4","5","6","7","8","9","10"],"results":["1","4","9","16","25","36","49","64","81","100"]}A more complete example can be found inexample.Details and explanationWhat?The goal is to help aiohttp users to build classes that will contain sessions object in an efficient/clean way.Why?If you want to build class that will make requests usingaiohttp client, at some point you'll have to deal with sessions.
Thequickstart guide for aiohttp clienthas an important note about them.importaiohttpasyncwithaiohttp.ClientSession()assession:asyncwithsession.get('http://httpbin.org/get')asresp:print(resp.status)print(awaitresp.text())...NoteDon’t create a session per request. Most likely you need a session per application which performs all requests altogether.More complex cases may require a session per site, e.g. one for Github and other one for Facebook APIs. Anyway making a session for every request is avery badidea.A session contains a connection pool inside. Connection reusage and keep-alives (both are on by default) may speed up total performance.The goal is to have a single session attached to a given object, this is what this module offers with only 3 (very simple) lines of code.How?The module provides an abstract classAbstractSessionContainerand a method decoratorattach_sessionthat you'll have to use to automatically add session management to an existing class.Say you have a classMathRequeststhat has a single methodget_squarethat returns the square value of the given parameter using anaiohttp.getrequest to the math API service located athttp://api.mathjs.org/v4. Here is what your class look like for now:importasyncio,aiohttproutes=aiohttp.web.RouteTableDef()classMathRequests:asyncdefget_text(self,url,params):# Remember "making a session for every request is a very bad idea"asyncwithaiohttp.ClientSession()assession:asyncwithsession.get(url,params=params)asresponse:returnawaitresponse.text()asyncdefget_square(self,value):returnawaitself.get_text("http://api.mathjs.org/v4",params={'expr':'{}^2'.format(value)})@routes.get('/squares')asyncdefindex(request):tasks=[]data=request.queryvalues=data['values'].split(',')maths=MathRequests()results=awaitasyncio.gather(*[maths.get_square(v)forvinvalues])returnweb.json_response({'values':values,'results':results})maths_app=aiohttp.web.Application()maths_app.add_routes(routes)Asaiohttpdocumentation says, this is a bad idea to implementMathRequeststhis way, we need to share a single session for allget_squarerequests.A simple solution to this would be to store a client session object withinMathRequests, which you could initiate in the__init__method. Saddly this is not a very clean solution as aiohttp sessions should be instantiated in a synchronous way (outside the even loop). Seeaiohttp#1468for more information aboutcreation a session outside of coroutine.Here is the final solution using the provided moduleasynctools:importasyncioimportasynctools# 1) Import# 2) Extends the abstract class that will handle the aiohttp session for you:classMathRequests(asynctools.AbstractSessionContainer):def__init__(self):# 2') (optional) initilise with any 'aiohttp.ClientSession' argumentsuper().__init__(raise_for_status=True)# 3) This decorator will automatically fill the session argument:@asynctools.attach_sessionasyncdefget_text(self,url,params,session=None):# 4) Add the 'session' argumentasyncwithsession.get(url,params=params)asresponse:returnawaitresponse.text()asyncdefget_square(self,value):returnawaitself.get_text("http://api.mathjs.org/v4",params={'expr':'{}^2'.format(value)})fromaiohttpimportwebroutes=web.RouteTableDef()@routes.get('/squares')asyncdefindex(request):tasks=[]data=request.queryvalues=data['values'].split(',')asyncwithMathRequests()asmaths:# Use the object as a context manager (async with <context_manager> as <name>)results=awaitasyncio.gather(*[maths.get_square(v)forvinvalues])returnweb.json_response({'values':values,'results':results})maths_app=web.Application()maths_app.add_routes(routes)Using theMathRequestsas acontext manageris the best option (as it will make sure the session is correctly started and closed), but it's not the only option, you can also keep your code as it was before:@routes.get('/squares')asyncdefindex(request):tasks=[]data=request.queryvalues=data['values'].split(',')maths=MathRequests()results=awaitasyncio.gather(*[maths.get_square(v)forvinvalues])returnweb.json_response({'values':values,'results':results})In this case, no session is attached to themathsobject and every call toget_squarewill use a different session (which is as bad as it was with the old version ofMathRequests). What you can do to avoid that is toexplicitly open a "math session"which will make allget_squarecalls to use the same session (also, don't forget to close the session when you are done):@routes.get('/maths')asyncdefindex(request):tasks=[]data=request.queryvalues=data['values'].split(',')maths=MathRequests()maths.start_session()results=awaitasyncio.gather(*[maths.get_square(v)forvinvalues])maths.close_session()returnweb.json_response({'values':values,'results':results}) |
aiohttp_auth | This library provides authorization and authentication middleware plugins for
aiohttp servers.These plugins are designed to be lightweight, simple, and extensible, allowing
the library to be reused regardless of the backend authentication mechanism.
This provides a familiar framework across projects.There are two middleware plugins provided by the library. The auth_middleware
plugin provides a simple system for authenticating a users credentials, and
ensuring that the user is who they say they are.The acl_middleware plugin provides a simple access control list authorization
mechanism, where users are provided access to different view handlers depending
on what groups the user is a member of.auth_middleware UsageThe auth_middleware plugin provides a simple abstraction for remembering and
retrieving the authentication details for a user across http requests.
Typically, an application would retrieve the login details for a user, and call
the remember function to store the details. These details can then be recalled
in future requests. A simplistic example of users stored in a python dict would
be:from aiohttp_auth import auth
from aiohttp import web
# Simplistic name/password map
db = {'user': 'password',
'super_user': 'super_password'}
async def login_view(request):
params = await request.post()
user = params.get('username', None)
if (user in db and
params.get('password', None) == db[user]):
# User is in our database, remember their login details
await auth.remember(request, user)
return web.Response(body='OK'.encode('utf-8'))
raise web.HTTPForbidden()User data can be verified in later requests by checking that their username is
valid explicity, or by using the auth_required decorator:async def check_explicitly_view(request):
user = await get_auth(request)
if user is None:
# Show login page
return web.Response(body='Not authenticated'.encode('utf-8'))
return web.Response(body='OK'.encode('utf-8'))
@auth.auth_required
async def check_implicitly_view(request):
# HTTPForbidden is raised by the decorator if user is not valid
return web.Response(body='OK'.encode('utf-8'))To end the session, the user data can be forgotten by using the forget
function:@auth.auth_required
async def logout_view(request):
await auth.forget(request)
return web.Response(body='OK'.encode('utf-8'))The actual mechanisms for storing the authentication credentials are passed as
a policy to the session manager middleware. New policies can be implemented
quite simply by overriding the AbstractAuthentication class. The aiohttp_auth
package currently provides two authentication policies, a cookie based policy
based loosely on mod_auth_tkt (Apache ticket module), and a second policy that
uses the aiohttp_session class to store authentication tickets.The cookie based policy (CookieTktAuthentication) is a simple mechanism for
storing the username of the authenticated user in a cookie, along with a hash
value known only to the server. The cookie contains the maximum age allowed
before the ticket expires, and can also use the IP address (v4 or v6) of the
user to link the cookie to that address. The cookies data is not encryptedd,
but only holds the username of the user and the cookies expiration time, along
with its security hash:def init(loop):
# Create a auth ticket mechanism that expires after 1 minute (60
# seconds), and has a randomly generated secret. Also includes the
# optional inclusion of the users IP address in the hash
policy = auth.CookieTktAuthentication(urandom(32), 60,
include_ip=True))
app = web.Application(loop=loop,
middlewares=[auth.auth_middleware(policy)])
app = web.Application()
app.router.add_route('POST', '/login', login_view)
app.router.add_route('GET', '/logout', logout_view)
app.router.add_route('GET', '/test0', check_explicitly_view)
app.router.add_route('GET', '/test1', check_implicitly_view)
return appThe SessionTktAuthentication policy provides many of the same features, but
stores the same ticket credentials in a aiohttp_session object, allowing
different storage mechanisms such as Redis storage, and
EncryptedCookieStorage:from aiohttp_session import get_session, session_middleware
from aiohttp_session.cookie_storage import EncryptedCookieStorage
def init(loop):
# Create a auth ticket mechanism that expires after 1 minute (60
# seconds), and has a randomly generated secret. Also includes the
# optional inclusion of the users IP address in the hash
policy = auth.SessionTktAuthentication(urandom(32), 60,
include_ip=True))
middlewares = [session_middleware(EncryptedCookieStorage(urandom(32))),
auth.auth_middleware(policy)]
app = web.Application(loop=loop, middlewares=middlewares)
...acl_middleware UsageThe acl_middleware plugin (provided by the aiohttp_auth library), is layered
on top of the auth_middleware plugin, and provides a access control list (ACL)
system similar to that used by the Pyramid WSGI module.Each user in the system is assigned a series of groups. Each group in the
system can then be assigned permissions that they are allowed (or not allowed)
to access. Groups and permissions are user defined, and need only be immutable
objects, so they can be strings, numbers, enumerations, or other immutable
objects.To specify what groups a user is a member of, a function is passed to the
acl_middleware factory which taks a user_id (as returned from the
auth.get_auth function) as a parameter, and expects a sequence of permitted ACL
groups to be returned. This can be a empty tuple to represent no explicit
permissions, or None to explicitly forbid this particular user_id. Note that
the user_id passed may be None if no authenticated user exists. Building apon
our example, a function may be defined as:from aiohttp_auth import acl
group_map = {'user': (,),
'super_user': ('edit_group',),}
async def acl_group_callback(user_id):
# The user_id could be None if the user is not authenticated, but in
# our example, we allow unauthenticated users access to some things, so
# we return an empty tuple.
return group_map.get(user_id, tuple())
def init(loop):
...
middlewares = [session_middleware(EncryptedCookieStorage(urandom(32))),
auth.auth_middleware(policy),
acl.acl_middleware(acl_group_callback)]
app = web.Application(loop=loop, middlewares=middlewares)
...Note that the ACL groups returned by the function will be modified by the
acl_middleware to also include the Group.Everyone group (if the value returned
is not None), and also the Group.AuthenticatedUser and user_id if the user_id
is not None.With the groups defined, a ACL context can be specified for looking up what
permissions each group is allowed to access. A context is a sequence of ACL
tuples which consist of a Allow/Deny action, a group, and a sequence of
permissions for that ACL group. For example:from aiohttp_auth.permissions import Group, Permission
context = [(Permission.Allow, Group.Everyone, ('view',)),
(Permission.Allow, Group.AuthenticatedUser, ('view', 'view_extra')),
(Permission.Allow, 'edit_group', ('view', 'view_extra', 'edit')),]Views can then be defined using the acl_required decorator, allowing only
specific users access to a particular view. The acl_required decorator
specifies a permission required to access the view, and a context to check
against:@acl_required('view', context)
async def view_view(request):
return web.Response(body='OK'.encode('utf-8'))
@acl_required('view_extra', context)
async def view_extra_view(request):
return web.Response(body='OK'.encode('utf-8'))
@acl_required('edit', context)
async def edit_view(request):
return web.Response(body='OK'.encode('utf-8'))In our example, non-logged in users will have access to the view_view, ‘user’
will have access to both the view_view and view_extra_view, and ‘super_user’
will have access to all three views. If no ACL group of the user matches the
ACL permission requested by the view, the decorator raises HTTPForbidden.ACL tuple sequences are checked in order, with the first tuple that matches the
group the user is a member of, AND includes the permission passed to the
function, declared to be the matching ACL group. This means that if the ACL
context was modified to:context = [(Permission.Allow, Group.Everyone, ('view',)),
(Permission.Deny, 'super_user', ('view_extra')),
(Permission.Allow, Group.AuthenticatedUser, ('view', 'view_extra')),
(Permission.Allow, 'edit_group', ('view', 'view_extra', 'edit')),]In this example the ‘super_user’ would be denied access to the view_extra_view
even though they are an AuthenticatedUser and in the edit_group.LicenseThe library is licensed under a MIT license. |
aiohttp_auth_autz | aiohttp_auth_autzThis library provides authorization and authentication middleware plugins for
aiohttp servers.These plugins are designed to be lightweight, simple, and extensible, allowing
the library to be reused regardless of the backend authentication mechanism.
This provides a familiar framework across projects.There are three middleware plugins provided by the library. Theauth_middlewareplugin provides a simple system for authenticating a users credentials, and
ensuring that the user is who they say they are.Theautz_middlewareplugin provides a generic way of authorization using
different authorization policies. There is the ACL authorization policy as a
part of the plugin.Theacl_middlewareplugin provides a simple access control list authorization
mechanism, where users are provided access to different view handlers depending
on what groups the user is a member of. It is recomended to useautz_middlewarewith ACL policy instead of this middleware.This is a fork ofaiohttp_authlibrary that fixes some bugs and security issues and also introduces a generic
authorizationautzmiddleware with built in ACL authorization policy.Documentationhttp://aiohttp-auth-autz.readthedocs.io/InstallInstallaiohttp_auth_autzusingpip:$ pip install aiohttp_auth_autzGetting StartedA simple example how to use authentication and authorization middleware
with an aiohttp application.importasynciofromosimporturandomimportaiohttp_authfromaiohttpimportwebfromaiohttp_authimportauth,autzfromaiohttp_auth.authimportauth_requiredfromaiohttp_auth.autzimportautz_requiredfromaiohttp_auth.autz.policyimportaclfromaiohttp_auth.permissionsimportPermission,Groupdb={'bob':{'password':'bob_password','groups':['guest','staff']},'alice':{'password':'alice_password','groups':['guest']}}# global ACL contextcontext=[(Permission.Allow,'guest',{'view',}),(Permission.Deny,'guest',{'edit',}),(Permission.Allow,'staff',{'view','edit','admin_view'}),(Permission.Allow,Group.Everyone,{'view_home',})]# create an ACL authorization policy classclassACLAutzPolicy(acl.AbstractACLAutzPolicy):"""The concrete ACL authorization policy."""def__init__(self,db,context=None):# do not forget to call parent __init__super().__init__(context)self.db=dbasyncdefacl_groups(self,user_identity):"""Return acl groups for given user identity.
This method should return a sequence of groups for given user_identity.
Args:
user_identity: User identity returned by auth.get_auth.
Returns:
Sequence of acl groups for the user identity.
"""# implement application specific logic hereuser=self.db.get(user_identity,None)ifuserisNone:# return empty tuple in order to give a chance# to Group.Everyonereturntuple()returnuser['groups']asyncdeflogin(request):# http://127.0.0.1:8080/login?username=bob&password=bob_passworduser_identity=request.GET.get('username',None)password=request.GET.get('password',None)ifuser_identityindbandpassword==db[user_identity]['password']:# remember user identityawaitauth.remember(request,user_identity)returnweb.Response(text='Ok')raiseweb.HTTPUnauthorized()# only authenticated users can logout# if user is not authenticated auth_required decorator# will raise a web.HTTPUnauthorized@auth_requiredasyncdeflogout(request):# forget user identityawaitauth.forget(request)returnweb.Response(text='Ok')# user should have a group with 'admin_view' permission allowed# if he does not autz_required will raise a web.HTTPForbidden@autz_required('admin_view')asyncdefadmin(request):returnweb.Response(text='Admin Page')@autz_required('view_home')asyncdefhome(request):text='Home page.'# check if current user is permitted with 'admin_view' permissionifawaitautz.permit(request,'admin_view'):text+=' Admin page: http://127.0.0.1:8080/admin'# get current user identityuser_identity=awaitauth.get_auth(request)ifuser_identityisnotNone:# user is authenticatedtext+=' Logout: http://127.0.0.1:8080/logout'returnweb.Response(text=text)# decorators can work with class based viewsclassMyView(web.View):"""Class based view."""@autz_required('view')asyncdefget(self):# example of permit usingifawaitautz.permit(self.request,'view'):returnweb.Response(text='View Page')returnweb.Response(text='View is not permitted')definit_app(loop):app=web.Application()# Create an auth ticket mechanism that expires after 1 minute (60# seconds), and has a randomly generated secret. Also includes the# optional inclusion of the users IP address in the hashauth_policy=auth.CookieTktAuthentication(urandom(32),60,include_ip=True)# Create an ACL authorization policyautz_policy=ACLAutzPolicy(db,context)# setup middlewares in aiohttp fashionaiohttp_auth.setup(app,auth_policy,autz_policy)app.router.add_get('/',home)app.router.add_get('/login',login)app.router.add_get('/logout',logout)app.router.add_get('/admin',admin)app.router.add_route('*','/view',MyView)returnapploop=asyncio.get_event_loop()app=init_app(loop)web.run_app(app,host='127.0.0.1',loop=loop)LicenseThe library is licensed under a MIT license.Changelog0.2.2 (2017-04-18)Move toaiohttp2.x.Add support of middlewares decorators foraiohttp.web.Viewhandlers.Adduvloopas IO loop for tests.0.2.1 (2017-02-16)autzmiddleware:Simplifyaclauthorization policy by moving permit logic intopolicy.acl.AbstractACLAutzPolicy.Removepolicy.acl.AbstractACLContextclass.Removepolicy.acl.NaiveACLContextclass.Removepolicy.acl.ACLContextclass.0.2.0 (2017-02-14)aclmiddleware:Addsetupfunction foraclmiddleware to install it in aiohttp fashion.Fix bug inacl_requireddecorator.Fix a possible security issue withaclgroups. The issue is follow: the default behavior is
to adduser_idto groups for authenticated users by the acl middleware, but ifuser_idis equal to some of acl groups that user suddenly has the permissions he is not
allowed for. So to avoid this kind of issueuser_idis not added to groups any more.IntroduceAbstractACLGroupsCallbackclass inaclmiddleware to make it possible easily create
callable object by inheriting from the abstract class and implementingacl_groupsmethod. It
can be useful to store additional information (such database connection etc.) within such class.
An instance of this subclass can be used in place ofacl_groups_callbackparameter.authmiddleware:Addsetupfunction forauthmiddleware to install it in aiohttp fashion.auth.auth_requiredraised now aweb.HTTPUnauthorizedinstead of aweb.HTTPForbidden.Introduce generic authorization middlewareautzthat performs authorization through the same
interface (autz.permitcoroutine andautz_requireddecorator) but using different policies.
Middleware has the ACL authorization as the built in policy which works in the same way asaclmiddleware. Users are free to add their own custom policies or to modify ACL one.Add globalaiohttp_auth.setupfunction to installauthandautzmiddlewares at once
in aiohttp fashion.Add docs.Rewrite tests usingpytestandpytest-aiohttp. |
aiohttp_autoreload | Makes aiohttp server autoreload on source code change.It’s very first, heavily untested version that should be used only in development.Code is taken from tornado.autoreload module.call_periodic module is taken from akaIDIOT’s gisthttps://gist.github.com/akaIDIOT/48c2474bd606cd2422caInstalationpip install aiohttp_autoreloadProposed usageimportasyncioimportaiohttp_autoreloaddebug=True# Or falseloop=asyncio.get_event_loop()handler=app.make_handler(debug=debug,)ifdebug:aiohttp_autoreload.start()f=loop.create_server(handler,'0.0.0.0',8080)... |
aiohttp-azure-logging | No description available on PyPI. |
aiohttpbabel | aiohttp_babel adds i18n and l10n support to aiohttp.Usage:importaiohttp_jinja2fromaiohttp.webimportApplicationfromaiohttp_babel.localeimport(load_gettext_translations,set_default_locale,set_locale_detector)fromaiohttp_babel.middlewaresimportbabel_middleware,_set_default_locale('en_GB')# set default locale, if necessary# load compiled localesload_gettext_translations('/path/to/locales','domain')# you can use your own locale detection method, if necessary.# aiohttp_babel checks cookie parameter `locale` or `Accept-Language`# header by default.defdetector(request):ifrequest.url.host=='es.example.com':return'es'elifrequest.url.host=='zh.example.com':return'zh'else:return'en'set_locale_detector(detector)jinja_loader=jinja2.FileSystemLoader('./templates')app=Application(middlewares=[babel_middleware])aiohttp_jinja2.setup(app,loader=jinja_loader)jinja_env=aiohttp_jinja2.get_env(app)jinja_env.globals['_']=_How to extract & compile locales:http://babel.pocoo.org/en/latest/messages.htmlhttp://babel.pocoo.org/en/latest/cmdline.htmlCode from:tornado-babel:https://github.com/openlabs/tornado-babeldjango-babel:https://github.com/python-babel/django-babel |
aiohttp-babel | No description available on PyPI. |
aiohttp-bam | HTTP basic authentication middleware for aiohttp.Parametersdef bam_factory(login, password, bypass_ws=False)创建一个basic auth的middlewarelogin:usernamepassword:passwordbypass_ws:绕过websocket请求,默认为Flase,不绕过Usage# server_simple.pyfromaiohttpimportwebfromaiohttp_bamimportbam_factoryasyncdefhandle(request):returnweb.Response(text="Hello")app=web.Application(middlewares=[bam_factory('your username','your password')])app.add_routes([web.get("/",handle)])web.run_app(app) |
aiohttp-baseapi | # aiohttp_baseapiThis is a micro framework for building HTTP APIs on a high level of abstraction on top of aiohttp.It allows to create jsonapi-like HTTP interface to models in declarative way and leaves it possible to fine tune at any level.## Quick startInstall the packagepip install aiohttp_baseapiCreates project directory structure in current directory (it also contains two sample apps)baseapi-start-projectInstall the dependenciescd src/pip install -r .meta/packagesConfigure Postgres DB connectionecho "DATABASE = {'host':'localhost','port':5432,'database':'test','user':'test','password':'test','minsize':1,'maxsize':10}" > ./settings_local.pyCreate migrationsalembic revision --autogenerate -m "init"Run migrationsalembic upgrade headRun the applicationpython ./main.py --port=9000That's it! You can try the API.It contains "default" app - it just prints all existing API methods under "/" location. And "demo" app - it contains two sample models.http GET :9000http POST :9000/authors <<< '{"data":{"name":"John", "surname": "Smith"}}'http POST :9000/books <<< '{"data":{"category": "Fiction","name":"Birthday","is_available":true, "author_id": 1}}'http GET ":9000/books?filter[name]=Birthday&include=authors"http GET :9000/books/1http PUT :9000/books/1 <<< '{"data":{"is_available":false}}'http DELETE :9000/books/1## FeaturesThere are some built-in features you can use:* filtration* sorting* fields selection* pagination* inclusion* validationRequest and response formats are inspired by jsonapi.org, but have some differences.Retrieved information can be filtered using `filter` GET-parameter.You can filter by multiple fields: `filter[fieldname1]=foo&filter[fieldname2]=bar`.In this case in response there are values for which the `fieldname1` equals to `foo` and `fieldname2` equals to `bar`.Also you can filter enumerating desired values: `filter[fieldname]=foo,bar`.In this case in response there are values for which the `fieldname` equals to `foo` or `bar`.Retrieved information can be sorted using `sort` GET-parameter.Also you can sort enumerating multiple values: `sort=fieldname1,-fieldname2`.In this case values in response will be sorted by `fieldname1` ascending, and then by `fieldname2` descending.Using parameter `fields` you can retrieve only those fields which you need.For example: `fields=fieldname1,fieldname2`. In this case values in response will have only `fieldname1` and `fieldname2` fields.Pagination (limit and offset) can be performed using `page` parameter.Usage: `page[limit]=10&page[offset]=20` - standard pagination (20 items skipped, maximum 10 returned).Also there is possibility to attach related entities using parameter `include`.One can apply described above features (filtration, sorting, etc.) to included entities. It will affect only included entities.Examples:`filter[entity.fieldname]=foo` - filtration;`sort[entity]=fieldname` - sorting;`fields[entity]=fieldname` - choosing fields;`page[entity.limit]=10` - pagination.The data passed in modifying requests (POST, PUT, etc.) can be validated using json-schema (which can be auto-generated from model description) or manually.Default data provider is database, but you can use anything you wish.## Unit testsRun:$ pip install -r .meta/packages_unit$ cd src$ make unit-test |
aiohttp-basicauth | aiohttp-basicauthHTTP basic authentication middleware for aiohttp 3.0+.
Inspired byFlask-BasicAuth.RequirementsPython >= 3.5.3aiohttp >= 3.0Installationpip install aiohttp_basicauthSimple usagefromaiohttpimportwebfromaiohttp_basicauthimportBasicAuthMiddlewareauth=BasicAuthMiddleware(username='user',password='password')app=web.Application(middlewares=[auth])web.run_app(app,host='127.0.0.1',port=80)Protect specific view(s)fromaiohttpimportwebfromaiohttp_basicauthimportBasicAuthMiddlewareauth=BasicAuthMiddleware(username='user',password='password',force=False)asyncdefpublic_view(request):returnweb.Response(text='Public view')@auth.requiredasyncdefsecret_view(request):returnweb.Response(text='Secret view')app=web.Application(middlewares=[auth])app.router.add_route('GET','/public',public_view)app.router.add_route('GET','/secret',secret_view)web.run_app(app,host='127.0.0.1',port=80)Advanced usageYou can overridecheck_credentialsmethod to implement more complex user verification logic:fromaiohttpimportwebfromaiohttp_basicauthimportBasicAuthMiddlewareclassCustomBasicAuth(BasicAuthMiddleware):asyncdefcheck_credentials(self,username,password,request):# here, for example, you can search user in the database by passed `username` and `password`, etc.returnusername=='user'andpassword=='password'auth=CustomBasicAuth()app=web.Application(middlewares=[auth])web.run_app(app,host='127.0.0.1',port=80) |
aiohttp-basicauth-middleware | Aiohttp middleware for simple http basic
auth protection for some urls.Works with Python >= 3.6.Works with UTF-8 🖖Installationpipinstallaiohttp-basicauth-middlewareUsageapp=web.Application(loop=loop)app.router.add_route('GET','/hello',handler_a)app.router.add_route('GET','/admin/hello',handler_b)app.middlewares.append(basic_auth_middleware(('/admin',),{'user':'password'},))basic_auth_middlewarehas 3 params:list of protected urls. For example[‘/admin’]will match
with/admin/user, but will not match with/user/admin.auth dict – a dict with pairs: login-password.strategy (optional) for password comparision. For example you can
store hashed password inauth_dict. Seeaiohttp_basicauth_middleware.strategy.BaseStrategyandexample.strategyfor more information.Example with md5 password hashing:app=web.Application(loop=loop)app.router.add_route('GET','/hello',handler_a)app.router.add_route('GET','/admin/hello',handler_b)app.middlewares.append(basic_auth_middleware(('/admin',),{'user':'5f4dcc3b5aa765d61d8327deb882cf99'},lambdax:hashlib.md5(bytes(x,encoding='utf-8')).hexdigest(),))/admin/…will be accessed by the same login+password pair (‘user’, ‘password’). |
aiohttp-boilerplate | No description available on PyPI. |
aiohttp-but-its-requests | aiohttp_but_its_requestsThe speed of aiohttp simplified to the level of requests.getaiohttp_but_its_requests.get(url)Returns aClientResponseobject.postaiohttp_but_its_requests.post(url, data)Returns aClientResponseobject.aiohttp_but_its_requests.delete(url)Returns aClientResponseobject.headaiohttp_but_its_requests.head(url)Returns aClientResponseobject.optionsaiohttp_but_its_requests.options(url)Returns aClientResponseobject. |
aiohttp-cache | Aiohttp-cacheWhat's aiohttp-cacheaiohttp-cacheis a plugin for aiohttp.web server that allow to use a
cache system to improve the performance of your site.How to use itWith in-memory backendimportasynciofromaiohttpimportwebfromaiohttp_cacheimport(# noqasetup_cache,cache,)PAYLOAD={"hello":"aiohttp_cache"}WAIT_TIME=2@cache()asyncdefsome_long_running_view(request:web.Request,)->web.Response:awaitasyncio.sleep(WAIT_TIME)payload=awaitrequest.json()returnweb.json_response(payload)app=web.Application()setup_cache(app)app.router.add_post("/",some_long_running_view)web.run_app(app)With redis backendNote: redis should be available at$CACHE_URLenv variable orredis://localhost:6379/0importasyncioimportyarlfromaiohttpimportwebfromenvparseimportenvfromaiohttp_cacheimport(# noqasetup_cache,cache,RedisConfig,)PAYLOAD={"hello":"aiohttp_cache"}WAIT_TIME=2@cache()asyncdefsome_long_running_view(request:web.Request,)->web.Response:awaitasyncio.sleep(WAIT_TIME)payload=awaitrequest.json()returnweb.json_response(payload)app=web.Application()url=yarl.URL(env.str("CACHE_URL",default="redis://localhost:6379/0"))setup_cache(app,cache_type="redis",backend_config=RedisConfig(db=int(url.path[1:]),host=url.host,port=url.port),)app.router.add_post("/",some_long_running_view)web.run_app(app)Example with a custom cache keyLet's say you would like to cache the requests just by the method and
json payload, then you can setup this as per the follwing example.Notedefault key_pattern is:DEFAULT_KEY_PATTERN=(AvailableKeys.method,AvailableKeys.host,AvailableKeys.path,AvailableKeys.postdata,AvailableKeys.ctype,)importasynciofromaiohttpimportwebfromaiohttp_cacheimport(setup_cache,cache,AvailableKeys,)# noqaPAYLOAD={"hello":"aiohttp_cache"}WAIT_TIME=2@cache()asyncdefsome_long_running_view(request:web.Request,)->web.Response:awaitasyncio.sleep(WAIT_TIME)payload=awaitrequest.json()returnweb.json_response(payload)custom_cache_key=(AvailableKeys.method,AvailableKeys.json)app=web.Application()setup_cache(app,key_pattern=custom_cache_key)app.router.add_post("/",some_long_running_view)web.run_app(app)Parametrize the cache decoratorimportasynciofromaiohttpimportwebfromaiohttp_cacheimport(# noqasetup_cache,cache,)PAYLOAD={"hello":"aiohttp_cache"}WAIT_TIME=2@cache(expires=1*24*3600,# in secondsunless=False,# anything what returns a bool. if True - skips cache)asyncdefsome_long_running_view(request:web.Request,)->web.Response:awaitasyncio.sleep(WAIT_TIME)payload=awaitrequest.json()returnweb.json_response(payload)app=web.Application()setup_cache(app)app.router.add_post("/",some_long_running_view)web.run_app(app)LicenseThis project is released under BSD license. Feel freeSource CodeThe latest developer version is available in a github repository:https://github.com/cr0hn/aiohttp-cacheDevelopment environmentdocker-compose run tests |
aiohttp_cas | UNKNOWN |
aiohttp-catcher | aiohttp-catcheraiohttp-catcher is a centralized error handler foraiohttp servers.
It enables consistent error handling across your web server or API, so your code can raise Python exceptions that
will be mapped to consistent, user-friendly error messages.QuickstartWhat's New in 0.3.0?Key FeaturesReturn a ConstantStringify the ExceptionCanned HTTP 4xx and 5xx Errors (aiohttp Exceptions)Callables and AwaitablesHandle Several Exceptions SimilarlyScenarios as DictionariesAdditional FieldsDefault for Unhandled ExceptionsDevelopmentTL;DR:QuickstartInstall aiohttp-catcher:pipinstallaiohttp-catcherStart catching errors in your aiohttp-based web server:fromaiohttpimportwebfromaiohttp_catcherimportcatch,Catcherasyncdefdivide(request):quotient=1/0returnweb.Response(text=f"1 / 0 ={quotient}")asyncdefmain():# Add a catcher:catcher=Catcher()# Register error-handling scenarios:awaitcatcher.add_scenario(catch(ZeroDivisionError).with_status_code(400).and_return("Zero division makes zero sense"))# Register your catcher as an aiohttp middleware:app=web.Application(middlewares=[catcher.middleware])app.add_routes([web.get("/divide-by-zero",divide)])web.run_app(app)Making a request to/divide-by-zerowill return a 400 status code with the following body:{"code":400,"message":"Zero division makes zero sense"}IMPORTANT NOTE:aiohttp's order of middleware mattersMiddlewares that are appended further in the list of your app's middlewares act
earlier. Consider the following example:app=web.Application(middlewares=[middleware1,middleware2])In the above case,middleware2will be triggered first, and only then
willmiddleware1be triggered. This means two things:If you register another middleware that catches exceptions but doesn't raise them
when it's done, you will need to add itbeforeyouraiohttp-catchermiddleware
or the other middleware will shadowaiohttp-catcher.If you register another middleware that relies on exceptions being raised, you want
to make sure it's addedafteryouraiohttp-catchermiddleware, to avoid having
youraiohttp-catchermiddleware shadow the other middleware. One good example isaiohttp-debugtoolbar, which, likeaiohttp-catcher, expects exceptions to be thrown and raises them when its middleware's
execution is done. In this case, you want to set upaiohttp-debugtoolbarafter appending
youraiohttp-catchermiddleware.What's New in 0.3.0?Canned Scenarios:You can now use acanned list of scenarios,
capturing all ofaiohttp's web exceptionsout of the box.More flexible Callables and Awaitables:Callables and Awaitables are now invoked with a second argument,the aiohttpRequestinstance, to add more flexibility to custom messages.Key FeaturesReturn a ConstantIn case you want some exceptions to return a constant message across your application, you can do
so by using theand_return("some value")method:awaitcatcher.add_scenario(catch(ZeroDivisionError).with_status_code(400).and_return("Zero division makes zero sense"))Stringify the ExceptionIn some cases, you would want to return a stringified version of your exception, should it entail
user-friendly information.classEntityNotFound(Exception):def__init__(self,entity_id,*args,**kwargs):super(EntityNotFound,self).__init__(*args,**kwargs)self.entity_id=entity_iddef__str__(self):returnf"Entity{self.entity_id}could not be found"@routes.get("/user/{user_id}")asyncdefget_user(request):user_id=request.match_info.get("user_id")ifuser_idnotinuser_db:raiseEntityNotFound(entity_id=user_id)returnuser_db[user_id]# Your catcher can be directed to stringify particular exceptions:awaitcatcher.add_scenario(catch(EntityNotFound).with_status_code(404).and_stringify())Canned HTTP 4xx and 5xx Errors (aiohttp Exceptions)As of version0.3.0, you
can registerall of aiohttp's web exceptions.
This is particularly useful when you want to ensure all possible HTTP errors are handled consistently.Register the canned HTTP errors in the following way:fromaiohttpimportwebfromaiohttp_catcherimportCatcherfromaiohttp_catcher.cannedimportAIOHTTP_SCENARIOSasyncdefmain():# Add a catcher:catcher=Catcher()# Register aiohttp web errors:awaitcatcher.add_scenario(*AIOHTTP_SCENARIOS)# Register your catcher as an aiohttp middleware:app=web.Application(middlewares=[catcher.middleware])web.run_app(app)Once you've registered the canned errors, you can rely on aiohttp-catcher to convert errors raised by aiohttp
to user-friendly error messages. For example,curling a non-existent route in your server will return the
following error out of the box:{"code":404,"message":"HTTPNotFound"}Callables and AwaitablesIn some cases, you'd want the message returned by your server for some exceptions to call a custom
function. This function can either be a synchronous function or an awaitable one. Your function should expect
two arguments:The exception being raised by handlers.The request object - an instance ofaiohttp.web.Request.fromaiohttp.webimportRequestfromaiohttp_catcherimportcatch,Catcher# Can be a synchronous function:asyncdefwrite_message(exc:Exception,request:Request):return"Whoops"catcher=Catcher()awaitcatcher.add_scenarios(catch(MyCustomException2).with_status_code(401).and_call(write_message),catch(MyCustomException2).with_status_code(403).and_call(lambdaexc:str(exc)))Handle Several Exceptions SimilarlyYou can handle several exceptions in the same manner by adding them to the same scenario:awaitcatcher.add_scenario(catch(MyCustomException1,MyCustomException2,MyCustomException3).with_status_code(418).and_return("User-friendly error message"))Scenarios as DictionariesYou can register your scenarios as dictionaries as well:awaitcatcher.add_scenarios({"exceptions":[ZeroDivisionError],"constant":"Zero division makes zero sense","status_code":400,},{"exceptions":[EntityNotFound],"stringify_exception":True,"status_code":404,},{"exceptions":[IndexError],"func":lambdaexc:f"Out of bound:{str(exc)}","status_code":418,},)Additional FieldsYou can enrich your error responses with additional fields. You can provide additional fields using
literal dictionaries or with callables. Your function should expect two arguments:The exception being raised by handlers.The request object - an instance ofaiohttp.web.Request.# Using a literal dictionary:awaitcatcher.add_scenario(catch(EntityNotFound).with_status_code(404).and_stringify().with_additional_fields({"error_code":"ENTITY_NOT_FOUND"}))# Using a function (or an async function):awaitcatcher.add_scenario(catch(EntityNotFound).with_status_code(404).and_stringify().with_additional_fields(lambdaexc,req:{"error_code":e.error_code,"method":req.method}))Default for Unhandled ExceptionsExceptions that aren't registered with scenarios in yourCatcherwill default to 500, with a payload similar to
the following:{"code":500,"message":"Internal server error"}DevelopmentContributions are warmly welcomed. Before submitting your PR, please run the tests using the following Make target:makeciAlternatively, you can run each test separately:Unit tests:maketest/pyLinting with pylint:makepylintStatic security checks with bandit:makepybandit |
aiohttp-clean-jwt | aiohttp-clean-jwtПростая аутентификация по JWT-токену для aiohttpИсточник вдохновения -aiohttp-jwtК сожалению, оригинальная библиотека плохо документирована, перегружена малопонятным функционалом и уже несколько лет выглядит заброшенной.Установка:pip install aiohttp_clean_jwtПример использования:fromaiohttpimportwebfromaiohttp.webimportApplication,Request,Responsefromaiohttp_clean_jwtimportget_token,json_response,middleware_factoryJWT_SECRET='top_secret_word'JWT_ALGORITHM='HS256'JWT_EXP_DELTA_SECONDS=360JWT_AUTH_SCHEME='Bearer'asyncdefget_user_id(login:str,password:str)->int:""" Проверка ID пользователя. В реальном приложении должна сходить в базу."""iflogin=='vasya'andpassword=='qwerty':return12345asyncdefsign_in(request:Request)->Response:""" Ручка авторизации """try:login=request.rel_url.query['login']password=request.rel_url.query['password']exceptKeyError:raiseweb.HTTPUnauthorized(reason='Missing credentials')user_id=awaitget_user_id(login=login,password=password)ifuser_idisnotNone:jwt_token=get_token({'user_id':str(user_id)},expiration_s=JWT_EXP_DELTA_SECONDS,algorithm=JWT_ALGORITHM,secret=JWT_SECRET)returnjson_response({'token':jwt_token})else:raiseweb.HTTPUnauthorized(reason='Wrong credentials')# Все ручки по умолчанию считаются приватными.# Чтобы сделать ручку публичной, ее нужно явным образом перечислить в whitelist.# Для доступа к приватным ручкам необходимо передавать полученный в /login токен через# HTTP HEADER "Authorization: Bearer"asyncdefstub1(request:Request)->Response:""" Приватная ручка 1"""user_id=request.rel_url.query['user_id']result={'user_id':user_id,'handler':'stub1'}returnjson_response(result)asyncdefstub2(request:Request)->Response:""" Приватная ручка 2"""user_id=request.rel_url.query['user_id']result={'user_id':user_id,'handler':'stub2'}returnjson_response(result)asyncdefpublic(request:Request)->Response:""" Публичная ручка"""result={'user_id':'anonymous','handler':'public'}returnjson_response(result)if__name__=='__main__':app=Application(middlewares=middleware_factory(whitelist=['/login','/public'],secret=JWT_SECRET,algorithm=JWT_ALGORITHM,auth_scheme=JWT_AUTH_SCHEME,))app.add_routes([web.get('/login',sign_in),web.get('/public',public),web.get('/stub1',stub1),web.get('/stub2',stub2)])web.run_app(app=app) |
aiohttpclient | No description available on PyPI. |
aiohttp-client-cache | aiohttp-client-cacheaiohttp-client-cacheis an async persistent cache foraiohttpclient requests, based onrequests-cache.FeaturesEase of use:Use as adrop-in replacementforaiohttp.ClientSessionCustomization:Works out of the box with little to no config, but with plenty of options
available for customizing cacheexpirationand otherbehaviorPersistence:Includes severalstorage backends:
SQLite, DynamoDB, MongoDB, DragonflyDB and Redis.QuickstartFirst, install with pip (python 3.8+ required):pipinstallaiohttp-client-cache[all]Note:Adding[all]will install optional dependencies for all supported backends. When adding this
library to your application, you can include only the dependencies you actually need; see individual
backend docs andpyproject.tomlfor details.Basic UsageNext, useaiohttp_client_cache.CachedSessionin place ofaiohttp.ClientSession.
To briefly demonstrate how to use it:Replace this:fromaiohttpimportClientSessionasyncwithClientSession()assession:awaitsession.get('http://httpbin.org/delay/1')With this:fromaiohttp_client_cacheimportCachedSession,SQLiteBackendasyncwithCachedSession(cache=SQLiteBackend('demo_cache'))assession:awaitsession.get('http://httpbin.org/delay/1')The URL in this example adds a delay of 1 second, simulating a slow or rate-limited website.
With caching, the response will be fetched once, saved todemo_cache.sqlite, and subsequent
requests will return the cached response near-instantly.ConfigurationSeveral options are available to customize caching behavior. This example demonstrates a few of them:# fmt: offfromaiohttp_client_cacheimportSQLiteBackendcache=SQLiteBackend(cache_name='~/.cache/aiohttp-requests.db',# For SQLite, this will be used as the filenameexpire_after=60*60,# By default, cached responses expire in an hoururls_expire_after={'*.fillmurray.com':-1},# Requests for any subdomain on this site will never expireallowed_codes=(200,418),# Cache responses with these status codesallowed_methods=['GET','POST'],# Cache requests with these HTTP methodsinclude_headers=True,# Cache requests with different headers separatelyignored_params=['auth_token'],# Keep using the cached response even if this param changestimeout=2.5,# Connection timeout for SQLite backend)More InfoTo learn more, see:User GuideCache BackendsAPI ReferenceExamplesFeedbackIf there is a feature you want, if you've discovered a bug, or if you have other general feedback, pleasecreate an issuefor it! |
aiohttp-client-manager | A module to automatically manageaiohttp.ClientSessionobjects for you
to improve performance.The package manages a global cache ofaiohttp.ClientSessionobjects based
on the host a particular request is connecting to so connections can be
reused between requests.It also simplifies the API.UsageThe usage is similar to the pythonrequestslibrary:import aiohttp_client
async with aiohttp_client.get('http://www.google.com') as resp:
# do something hereConfigurationUses env variables to configure max number of reqeusts/sessions to manage:AIOHTTP_SESSION_SIZE: max number of sessions to keep in cache(default 200)AIOHTTP_SESSION_DNS_CACHE: number of seconds to keep dns lookup in cache(default 20)AIOHTTP_SESSION_LIMIT: number of simultaneous connections to have per session(default 500)1.1.2 (2022-10-20)Change to bsd license1.1.1 (2020-04-15)better session connector defaults1.1.0 (2019-06-06)update max requests and sessionsUpdated setup.py to point to aihttp_client.py1.0.0 (2018-04-09)initial release |
aiohttp-client-rate-limiter | aiohttp_client_rate_limiterThis is a mini tool that overwrites ClientSession class from aiohttp (https://pypi.org/project/aiohttp/). This subclass introduces rate limter functionality while leaving all the other parent behaviors untouched.Example:importasynciofromaiohttp_client_rate_limiter.ClientSessionimportRateLimitedClientSessionrl_session=RateLimitedClientSession(max_concur=5,reqs_per_period=10,period_in_secs=60)tasks=[asyncio.create_task(rl_session.get(f"https://www.google.com/?q={i}",ssl=False))foriinrange(10)]awaitasyncio.gather(*tasks)awaitrl_session.close()Or, we could simply do this, using the native context manager as provided by aiohttp:importasynciofromaiohttp_client_rate_limiter.ClientSessionimportRateLimitedClientSessionasyncwithRateLimitedClientSession(max_concur=60,reqs_per_period=5,period_in_secs=10)asrl_session:tasks=[asyncio.create_task(rl_session.get(f"https://www.google.com/?q={i}",ssl=False))foriinrange(10)]awaitasyncio.gather(*tasks)The above example could provide a steady rate of 10 requests/60 seconds at the maximum concurrency of 5. |
aiohttp-compress | aiohttp-compressThis module is the simplest way to enable compression support foraiohttpserver applications globally.Installationpipinstallaiohttp-compressExamplefromaiohttpimportwebfromaiohttp_compressimportcompress_middlewareasyncdefhandle(request):name=request.match_info.get('name',"Anonymous")text="Hello, "+namereturnweb.Response(text=text)app=web.Application()app.middlewares.append(compress_middleware)app.add_routes([web.get('/',handle),web.get('/{name}',handle)])if__name__=='__main__':web.run_app(app) |
aiohttp-cookauth | The library is a fork ofaiohttp_sessionandaiohttp_security. The fork provides identity and authorization foraiohttp.webonly via cookies using redis storage.Featuresadded the ability to forget all user sessions using forget_all functioncheck_permission function return userid nowInstallation$ pip install aiohttp_cookauthExamplefrom aiohttp import web
from aioredis import create_redis_pool
from aiohttp_cookauth import check_permission, \
is_anonymous, remember, forget, \
setup as setup_cookauth, RedisStorage, forget_all
from aiohttp_cookauth.abc import AbstractAuthorizationPolicy
# Demo authorization policy for only one user.
# User 'jack' has only 'listen' permission.
class SimpleJack_AuthorizationPolicy(AbstractAuthorizationPolicy):
async def authorized_userid(self, identity):
"""Retrieve authorized user id.
Return the user_id of the user identified by the identity
or 'None' if no user exists related to the identity.
"""
if identity == 'jack':
return identity
async def permits(self, identity, permission, context=None):
"""Check user permissions.
Return True if the identity is allowed the permission
in the current context, else return False.
"""
return identity == 'jack' and permission in ('listen',)
async def handler_root(request):
is_logged = not await is_anonymous(request)
return web.Response(text='''<html><head></head><body>
Hello, I'm Jack, I'm {logged} logged in.<br /><br />
<a href="/login">Log me in</a><br />
<a href="/logout">Log me out</a><br />
<a href="/logout/all">Log out for all</a><br /><br />
Check my permissions,
when i'm logged in and logged out.<br />
<a href="/listen">Can I listen?</a><br />
<a href="/speak">Can I speak?</a><br />
</body></html>'''.format(
logged='' if is_logged else 'NOT',
), content_type='text/html')
async def handler_login_jack(request):
redirect_response = web.HTTPFound('/')
await remember(request, redirect_response, 'jack')
return redirect_response
async def handler_logout(request):
redirect_response = web.HTTPFound('/')
await forget(request, redirect_response)
return redirect_response
async def handler_logout_all(request):
redirect_response = web.HTTPFound('/')
await forget_all(request, identity='jack')
return redirect_response
async def handler_listen(request):
await check_permission(request, 'listen')
return web.Response(body="I can listen!")
async def handler_speak(request):
await check_permission(request, 'speak')
return web.Response(body="I can speak!")
async def make_app():
# make app
app = web.Application()
# add the routes
app.add_routes([
web.get('/', handler_root),
web.get('/login', handler_login_jack),
web.get('/logout', handler_logout),
web.get('/logout/all', handler_logout_all),
web.get('/listen', handler_listen),
web.get('/speak', handler_speak)])
# set up policies
redis = await create_redis_pool(('localhost', 6379))
storage = RedisStorage(redis, cookie_name='MY_SESSION', max_age=900)
setup_cookauth(app, SimpleJack_AuthorizationPolicy(), storage)
return app
if __name__ == '__main__':
web.run_app(make_app(), port=9000)DocumentationUse aiohttp_security documentation:https://aiohttp-security.readthedocs.io/Licenseaiohttp_cookauthis offered under the Apache 2 license. |
aiohttp_cors | CORS support for aiohttpaiohttp_corslibrary implementsCross Origin Resource Sharing (CORS)support foraiohttpasyncio-powered asynchronous HTTP server.Jump directly toUsagepart to see how to useaiohttp_cors.Same-origin policyWeb security model is tightly connected toSame-origin policy (SOP).
In short: web pages cannotReadresources which origin
doesn’t match origin of requested page, but canEmbed(orExecute)
resources and have limited ability toWriteresources.Origin of a page is defined in theStandardas tuple(schema, host, port)(there is a notable exception with Internet Explorer: it doesn’t use port to
define origin, but uses it’s ownSecurity Zones).CanEmbedmeans that resource from other origin can be embedded into
the page,
e.g. by using<scriptsrc="...">,<imgsrc="...">,<iframesrc="...">.CannotReadmeans that resource from other originsourcecannot be
obtained by page
(source— any information that would allow to reconstruct resource).
E.g. the page canEmbedimage with<imgsrc="...">,
but it can’t get information about specific pixels, so page can’t reconstruct
original image
(though some information from the other resource may still be leaked:
e.g. the page can read embedded image dimensions).Limited ability toWritemeans, that the page can send POST requests to
other origin with limited set ofContent-Typevalues and headers.Restriction toReadresource from other origin is related to authentication
mechanism that is used by browsers:
when browser reads (downloads) resource he automatically sends all security
credentials that user previously authorized for that resource
(e.g. cookies, HTTP Basic Authentication).For example, ifReadwould be allowed and user is authenticated
in some internet banking,
malicious page would be able to embed internet banking page withiframe(since authentication is done by the browser it may be embedded as if
user is directly navigated to internet banking page),
then read user private information by readingsourceof the embedded page
(which may be not only source code, but, for example,
screenshot of the embedded internet banking page).Cross-origin resource sharingCross-origin Resource Sharing (CORS)allows to override
SOP for specific resources.In short, CORS works in the following way.When pagehttps://client.example.comrequest (Read) resourcehttps://server.example.com/resourcethat have other origin,
browser implicitly appendsOrigin:https://client.example.comheader
to the HTTP request,
effectively requesting server to give read permission for
the resource to thehttps://client.example.compage:GET /resource HTTP/1.1
Origin: https://client.example.com
Host: server.example.comIf server allows access from the page to the resource, it responds with
resource withAccess-Control-Allow-Origin:https://client.example.comHTTP header
(optionally allowing exposing custom server headers to the page and
enabling use of the user credentials on the server resource):Access-Control-Allow-Origin: https://client.example.com
Access-Control-Allow-Credentials: true
Access-Control-Expose-Headers: X-Server-HeaderBrowser checks, if server responded with properAccess-Control-Allow-Originheader and accordingly allows or denies
access for the obtained resource to the page.CORS specification designed in a way that servers that are not aware
of CORS will not expose any additional information, except allowed by the
SOP.To request resources with custom headers or using custom HTTP methods
(e.g.PUT,DELETE) that are not allowed by SOP,
CORS-enabled browser first sendpreflight requestto the
resource usingOPTIONSmethod, in which he queries access to the resource
with specific method and headers:OPTIONS / HTTP/1.1
Origin: https://client.example.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: X-Client-HeaderCORS-enabled server responds is requested method is allowed and which of
the specified headers are allowed:Access-Control-Allow-Origin: https://client.example.com
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: PUT
Access-Control-Allow-Headers: X-Client-Header
Access-Control-Max-Age: 3600Browser checks response to preflight request, and, if actual request allowed,
does actual request.InstallationYou can installaiohttp_corsas a typical Python library from PyPI or
from git:$pipinstallaiohttp_corsNote thataiohttp_corsrequires versions of Python >= 3.4.1 andaiohttp>= 1.1.UsageTo useaiohttp_corsyou need to configure the application and
enable CORS onresources and routesthat you want to expose:importasynciofromaiohttpimportwebimportaiohttp_cors@asyncio.coroutinedefhandler(request):returnweb.Response(text="Hello!",headers={"X-Custom-Server-Header":"Custom data",})app=web.Application()# `aiohttp_cors.setup` returns `aiohttp_cors.CorsConfig` instance.# The `cors` instance will store CORS configuration for the# application.cors=aiohttp_cors.setup(app)# To enable CORS processing for specific route you need to add# that route to the CORS configuration object and specify its# CORS options.resource=cors.add(app.router.add_resource("/hello"))route=cors.add(resource.add_route("GET",handler),{"http://client.example.org":aiohttp_cors.ResourceOptions(allow_credentials=True,expose_headers=("X-Custom-Server-Header",),allow_headers=("X-Requested-With","Content-Type"),max_age=3600,)})Each route has it’s own CORS configuration passed inCorsConfig.add()method.CORS configuration is a mapping from origins to options for that origins.In the example above CORS is configured for the resource under path/helloand HTTP methodGET, and in the context of CORS:This resource will be available using CORS only tohttp://client.example.orgorigin.Passing of credentials to this resource will be allowed.The resource will expose to the clientX-Custom-Server-Headerserver header.The client will be allowed to passX-Requested-WithandContent-Typeheaders to the server.Preflight requests will be allowed to be cached by client for3600seconds.Resource will be available only to the explicitly specified origins.
You can specify “all other origins” using special*origin:cors.add(route,{"*":aiohttp_cors.ResourceOptions(allow_credentials=False),"http://client.example.org":aiohttp_cors.ResourceOptions(allow_credentials=True),})Here the resource specified byroutewill be available to all origins with
disallowed credentials passing, and with allowed credentials passing only tohttp://client.example.org.By defaultResourceOptionswill be constructed without any allowed CORS
options.
This means, that resource will be available using CORS to specified origin,
but client will not be allowed to send either credentials,
or send non-simple headers, or read from server non-simple headers.To enable sending or receiving all headers you can specify special value*instead of sequence of headers:cors.add(route,{"http://client.example.org":aiohttp_cors.ResourceOptions(expose_headers="*",allow_headers="*"),})You can specify default CORS-enabled resource options usingaiohttp_cors.setup()’sdefaultsargument:cors=aiohttp_cors.setup(app,defaults={# Allow all to read all CORS-enabled resources from# http://client.example.org."http://client.example.org":aiohttp_cors.ResourceOptions(),})# Enable CORS on routes.# According to defaults POST and PUT will be available only to# "http://client.example.org".hello_resource=cors.add(app.router.add_resource("/hello"))cors.add(hello_resource.add_route("POST",handler_post))cors.add(hello_resource.add_route("PUT",handler_put))# In addition to "http://client.example.org", GET request will be# allowed from "http://other-client.example.org" origin.cors.add(hello_resource.add_route("GET",handler),{"http://other-client.example.org":aiohttp_cors.ResourceOptions(),})# CORS will be enabled only on the resources added to `CorsConfig`,# so following resource will be NOT CORS-enabled.app.router.add_route("GET","/private",handler)Also you can specify default options for resources:# Allow POST and PUT requests from "http://client.example.org" origin.hello_resource=cors.add(app.router.add_resource("/hello"),{"http://client.example.org":aiohttp_cors.ResourceOptions(),})cors.add(hello_resource.add_route("POST",handler_post))cors.add(hello_resource.add_route("PUT",handler_put))Resource CORS configuration allows to useallow_methodsoption that
explicitly specifies list of allowed HTTP methods for origin
(or*for all HTTP methods).
By using this option it is not required to add all resource routes to
CORS configuration object:# Allow POST and PUT requests from "http://client.example.org" origin.hello_resource=cors.add(app.router.add_resource("/hello"),{"http://client.example.org":aiohttp_cors.ResourceOptions(allow_methods=["POST","PUT"]),})# No need to add POST and PUT routes into CORS configuration object.hello_resource.add_route("POST",handler_post)hello_resource.add_route("PUT",handler_put)# Still you can add additional methods to CORS configuration object:cors.add(hello_resource.add_route("DELETE",handler_delete))Here is an example of how to enable CORS for all origins with all CORS
features:cors=aiohttp_cors.setup(app,defaults={"*":aiohttp_cors.ResourceOptions(allow_credentials=True,expose_headers="*",allow_headers="*",)})# Add all resources to `CorsConfig`.resource=cors.add(app.router.add_resource("/hello"))cors.add(resource.add_route("GET",handler_get))cors.add(resource.add_route("PUT",handler_put))cors.add(resource.add_route("POST",handler_put))cors.add(resource.add_route("DELETE",handler_delete))Old routes API is supported — you can userouter.add_routerandrouter.register_routeas before, though this usage is discouraged:cors.add(app.router.add_route("GET","/hello",handler),{"http://client.example.org":aiohttp_cors.ResourceOptions(allow_credentials=True,expose_headers=("X-Custom-Server-Header",),allow_headers=("X-Requested-With","Content-Type"),max_age=3600,)})You can enable CORS for all added routes by accessing routes list
in the router:# Setup application routes.app.router.add_route("GET","/hello",handler_get)app.router.add_route("PUT","/hello",handler_put)app.router.add_route("POST","/hello",handler_put)app.router.add_route("DELETE","/hello",handler_delete)# Configure default CORS settings.cors=aiohttp_cors.setup(app,defaults={"*":aiohttp_cors.ResourceOptions(allow_credentials=True,expose_headers="*",allow_headers="*",)})# Configure CORS on all routes.forrouteinlist(app.router.routes()):cors.add(route)You can also useCorsViewMixinonweb.View:classCorsView(web.View,CorsViewMixin):cors_config={"*":ResourceOption(allow_credentials=True,allow_headers="X-Request-ID",)}@asyncio.coroutinedefget(self):returnweb.Response(text="Done")@custom_cors({"*":ResourceOption(allow_credentials=True,allow_headers="*",)})@asyncio.coroutinedefpost(self):returnweb.Response(text="Done")cors=aiohttp_cors.setup(app,defaults={"*":aiohttp_cors.ResourceOptions(allow_credentials=True,expose_headers="*",allow_headers="*",)})cors.add(app.router.add_route("*","/resource",CorsView),webview=True)SecurityTODO: fill thisDevelopmentTo setup development environment:# Clone sources repository:gitclonehttps://github.com/aio-libs/aiohttp_cors.git.# Create and activate virtual Python environment:python3-mvenvenvsourceenv/bin/activate# Install requirements and aiohttp_cors into virtual environmentpipinstall-rrequirements-dev.txtTo run tests:toxTo run only runtime tests in current environment:py.testTo run only static code analysis checks:tox-echeckRunning Selenium testsTo run Selenium tests with Firefox web driver you need to install Firefox.To run Selenium tests with Chromium web driver you need to:Install Chrome driver. On Ubuntu 14.04 it’s inchromium-chromedriverpackage.Either addchromedriverto PATH or setWEBDRIVER_CHROMEDRIVER_PATHenvironment variable tochromedriver, e.g. on Ubuntu 14.04WEBDRIVER_CHROMEDRIVER_PATH=/usr/lib/chromium-browser/chromedriver.Release processTo release versionvA.B.Cfrom the current version ofmasterbranch
you need to:Create local branchvA.B.C.InCHANGES.rstset release date to today.Inaiohttp_cors/__about__.pychange version fromA.B.Ca0toA.B.C.Create pull request withvA.B.Cbranch, wait for all checks to
successfully finish (Travis and Appveyor).Merge pull request to master.Update and checkoutmasterbranch.Create and push tag for release version to GitHub:gittagvA.B.Cgitpush--tagsNow Travis should ran tests again, and build and deploy wheel on PyPI.If Travis release doesn’t work for some reason, use following steps
for manual release upload.Install fresh versions of setuptools and pip.
Installwheelfor building wheels.
Installtwinefor uploading to PyPI.pipinstall-UpipsetuptoolstwinewheelConfigure PyPI credentials in~/.pypirc.Build distribution:rm-rfbuilddist;pythonsetup.pysdistbdist_wheelUpload new release to PyPI:twineuploaddist/*Edit release description on GitHub if needed.Announce new release on theaio-libsmailing list:https://groups.google.com/forum/#!forum/aio-libs.Post release steps:InCHANGES.rstadd template for the next release.Inaiohttp_cors/__about__.pychange version fromA.B.CtoA.(B+1).0a0.BugsPlease report bugs, issues, feature requests, etc. onGitHub.LicenseCopyright 2015 Vladimir Rutsky <[email protected]>.Licensed under theApache License, Version 2.0,
seeLICENSEfile for details.CHANGES0.7.0 (2018-03-05)Make web view check implicit and type based (#159)Disable Python 3.4 support (#156)Support aiohttp 3.0+ (#155)0.6.0 (2017-12-21)Support aiohttp views byCorsViewMixin(#145)0.5.3 (2017-04-21)Fixtypingbeing installed on Python 3.6.0.5.2 (2017-03-28)Fix tests compatibility withaiohttp2.0.
This release and release v0.5.0 should work onaiohttp2.0.0.5.1 (2017-03-23)Enforceaiohttpversion to be less than 2.0.
Neweraiohttpreleases will be supported in the next release.0.5.0 (2016-11-18)Fix compatibility withaiohttp1.10.4.0 (2016-04-04)Fixed support with new Resources objects introduced inaiohttp0.21.0.
Minimum supported version ofaiohttpis 0.21.4 now.New Resources objects are supported.
You can specify default configuration for a Resource and useallow_methodsto explicitly list allowed methods (or*for all
HTTP methods):# Allow POST and PUT requests from "http://client.example.org" origin.hello_resource=cors.add(app.router.add_resource("/hello"),{"http://client.example.org":aiohttp_cors.ResourceOptions(allow_methods=["POST","PUT"]),})# No need to add POST and PUT routes into CORS configuration object.hello_resource.add_route("POST",handler_post)hello_resource.add_route("PUT",handler_put)# Still you can add additional methods to CORS configuration object:cors.add(hello_resource.add_route("DELETE",handler_delete))AbstractRouterAdapterwas completely rewritten to be more Router
agnostic.0.3.0 (2016-02-06)RenameUrlDistatcherRouterAdaptertoUrlDispatcherRouterAdapter.Set maximum supportedaiohttpversion to0.20.2, see bug #30 for
details.0.2.0 (2015-11-30)Move ABCs fromaiohttp_cors.router_adaptertoaiohttp_cors.abc.RenameRouterAdaptertoAbstractRouterAdapter.Fix bug with configuring CORS for named routes.0.1.0 (2015-11-05)Initial release. |
aiohttp-csrf | aiohttp_csrfThe library provides csrf (xsrf) protection foraiohttp.web.Breaking Change:New in 0.1.0 is Blake3 hashes are used by default. This means you must passsecret_phrasetoaiohttp_csrf.storage.SessionStoragenote:The packageaiohttp-csrf-fixedis aiohttp_csrf 0.0.2 +this commit. The maintainer
didn't submit a PR so I just saw it by chance. I haven't had time to closely examine it but I think it's just removing
the HTTP security error that happens if no CSRF is provided. Why do that? An HTTP error is good because it tells the
client what happened and lets you handle it by middleware.0.1.1:Converted@aiohttp_csrf.csrf_exemptdecorator to a co-routine to make it compatible with latest aiohttp.Basic usageThe library allows you to implement csrf (xsrf) protection for requestsBasic usage example:importaiohttp_csrffromaiohttpimportwebFORM_FIELD_NAME='_csrf_token'COOKIE_NAME='csrf_token'defmake_app():csrf_policy=aiohttp_csrf.policy.FormPolicy(FORM_FIELD_NAME)csrf_storage=aiohttp_csrf.storage.CookieStorage(COOKIE_NAME)app=web.Application()aiohttp_csrf.setup(app,policy=csrf_policy,storage=csrf_storage)app.middlewares.append(aiohttp_csrf.csrf_middleware)asyncdefhandler_get_form_with_token(request):token=awaitaiohttp_csrf.generate_token(request)body='''<html><head><title>Form with csrf protection</title></head><body><form method="POST" action="/"><input type="hidden" name="{field_name}" value="{token}" /><input type="text" name="name" /><input type="submit" value="Say hello"></form></body></html>'''# noqabody=body.format(field_name=FORM_FIELD_NAME,token=token)returnweb.Response(body=body.encode('utf-8'),content_type='text/html',)asyncdefhandler_post_check(request):post=awaitrequest.post()body='Hello,{name}'.format(name=post['name'])returnweb.Response(body=body.encode('utf-8'),content_type='text/html',)app.router.add_route('GET','/',handler_get_form_with_token,)app.router.add_route('POST','/',handler_post_check,)returnappweb.run_app(make_app())InitializeFirst of all, you need to initializeaiohttp_csrfin your application:app=web.Application()csrf_policy=aiohttp_csrf.policy.FormPolicy(FORM_FIELD_NAME)csrf_storage=aiohttp_csrf.storage.CookieStorage(COOKIE_NAME)aiohttp_csrf.setup(app,policy=csrf_policy,storage=csrf_storage)Middleware and decoratorsAfter initialize you can use@aiohttp_csrf.csrf_protectfor handlers, that you want to protect. Or you can
initializeaiohttp_csrf.csrf_middlewareand do not disturb about using
decorator (full middleware example here):# ...app.middlewares.append(aiohttp_csrf.csrf_middleware)# ...In this case all your handlers will be protected.Note:we strongly recommend to useaiohttp_csrf.csrf_middlewareand@aiohttp_csrf.csrf_exemptinstead of
manually managing with@aiohttp_csrf.csrf_protect. But if you prefer to use@aiohttp_csrf.csrf_protect, don't forget
to use@aiohttp_csrf.csrf_protectfor both methods: GET and
POST (manual protection example)If you want to use middleware, but need handlers without protection, you can use@aiohttp_csrf.csrf_exempt. Mark you
handler with this decorator and this handler will not check the token:@aiohttp_csrf.csrf_exemptasyncdefhandler_post_not_check(request):...Generate tokenFor generate token you need to callaiohttp_csrf.generate_tokenin your handler:@aiohttp_csrf.csrf_protectasyncdefhandler_get(request):token=awaitaiohttp_csrf.generate_token(request)...Advanced usagePoliciesYou can use different policies for check tokens. Library provides 3 types of policy:FormPolicy. This policy will search token in the body of your POST request (Usually use for forms) or as a GET
variable of the same name. You need to specify name of field that will be checked.HeaderPolicy. This policy will search token in headers of your POST request (Usually use for AJAX requests). You
need to specify name of header that will be checked.FormAndHeaderPolicy. This policy combines behavior ofFormPolicyandHeaderPolicy.You can implement your custom policies if needed. But make sure that your custom policy
implementsaiohttp_csrf.policy.AbstractPolicyinterface.StoragesYou can use different types of storages for storing token. Library provides 2 types of storage:CookieStorage. Your token will be stored in cookie variable. You need to specify cookie name.SessionStorage. Your token will be stored in session. You need to specify session variable name.Important:If you want to use session storage, you need setup aiohttp_session in your
application (session storage example)You can implement your custom storages if needed. But make sure that your custom storage
implementsaiohttp_csrf.storage.AbstractStorageinterface.Token generatorsYou can use different token generator in your application. By default storages
usingaiohttp_csrf.token_generator.SimpleTokenGeneratorBut if you need more secure token generator - you can useaiohttp_csrf.token_generator.HashedTokenGeneratorAnd you can implement your custom token generators if needed. But make sure that your custom token generator
implementsaiohttp_csrf.token_generator.AbstractTokenGeneratorinterface.Invalid token behaviorBy default, if token is invalid,aiohttp_csrfwill raiseaiohttp.web.HTTPForbiddenexception.You have ability to specify your custom error handler. It can be:callable instance. Input parameter - aiohttp request.defcustom_error_handler(request):# do somethingreturnaiohttp.web.Response(status=403)# orasyncdefcustom_async_error_handler(request):# await do somethingreturnaiohttp.web.Response(status=403)It will be called instead of protected handler.sub class of Exception. In this case this Exception will be raised.classCustomException(Exception):passYou can specify custom error handler globally, when initializeaiohttp_csrfin your application:...classCustomException(Exception):pass...aiohttp_csrf.setup(app,policy=csrf_policy,storage=csrf_storage,error_renderer=CustomException)...In this case custom error handler will be applied to all protected handlers.Or you can specify custom error handler locally, for specific handler:...classCustomException(Exception):pass...@aiohttp_csrf.csrf_protect(error_renderer=CustomException)defhandler_with_custom_csrf_error(request):...In this case custom error handler will be applied to this handler only. For all other handlers will be applied global
error handler. |
aiohttp-csrf-fixed | The library provides csrf (xsrf) protection foraiohttp.web.Basic usageThe library allows you to implement csrf (xsrf) protection for requestsBasic usage example:importaiohttp_csrffromaiohttpimportwebFORM_FIELD_NAME='_csrf_token'COOKIE_NAME='csrf_token'defmake_app():csrf_policy=aiohttp_csrf.policy.FormPolicy(FORM_FIELD_NAME)csrf_storage=aiohttp_csrf.storage.CookieStorage(COOKIE_NAME)app=web.Application()aiohttp_csrf.setup(app,policy=csrf_policy,storage=csrf_storage)app.middlewares.append(aiohttp_csrf.csrf_middleware)asyncdefhandler_get_form_with_token(request):token=awaitaiohttp_csrf.generate_token(request)body='''
<html>
<head><title>Form with csrf protection</title></head>
<body>
<form method="POST" action="/">
<input type="hidden" name="{field_name}" value="{token}" />
<input type="text" name="name" />
<input type="submit" value="Say hello">
</form>
</body>
</html>
'''# noqabody=body.format(field_name=FORM_FIELD_NAME,token=token)returnweb.Response(body=body.encode('utf-8'),content_type='text/html',)asyncdefhandler_post_check(request):post=awaitrequest.post()body='Hello,{name}'.format(name=post['name'])returnweb.Response(body=body.encode('utf-8'),content_type='text/html',)app.router.add_route('GET','/',handler_get_form_with_token,)app.router.add_route('POST','/',handler_post_check,)returnappweb.run_app(make_app())InitializeFirst of all, you need to initializeaiohttp_csrfin your application:app=web.Application()csrf_policy=aiohttp_csrf.policy.FormPolicy(FORM_FIELD_NAME)csrf_storage=aiohttp_csrf.storage.CookieStorage(COOKIE_NAME)aiohttp_csrf.setup(app,policy=csrf_policy,storage=csrf_storage)Middleware and decoratorsAfter initialize you can use@aiohttp_csrf.csrf_protectfor handlers, that you want to protect.
Or you can initializeaiohttp_csrf.csrf_middlewareand do not disturb about using decorator (full middleware example here):...app.middlewares.append(aiohttp_csrf.csrf_middleware)...In this case all your handlers will be protected.Note:we strongly recommend to useaiohttp_csrf.csrf_middlewareand@aiohttp_csrf.csrf_exemptinstead of manually managing with@aiohttp_csrf.csrf_protect.
But if you prefer to use@aiohttp_csrf.csrf_protect, don’t forget to use@aiohttp_csrf.csrf_protectfor both methods: GET and POST
(manual protection example)If you want to use middleware, but need handlers without protection, you can use@aiohttp_csrf.csrf_exempt.
Mark you handler with this decorator and this handler will not check the token:@aiohttp_csrf.csrf_exemptasyncdefhandler_post_not_check(request):...Generate tokenFor generate token you need to callaiohttp_csrf.generate_tokenin your handler:@aiohttp_csrf.csrf_protectasyncdefhandler_get(request):token=awaitaiohttp_csrf.generate_token(request)...Advanced usagePoliciesYou can use different policies for check tokens. Library provides 3 types of policy:FormPolicy. This policy will search token in the body of your POST request (Usually use for forms) or as a GET variable of the same name. You need to specify name of field that will be checked.HeaderPolicy. This policy will search token in headers of your POST request (Usually use for AJAX requests). You need to specify name of header that will be checked.FormAndHeaderPolicy. This policy combines behavior ofFormPolicyandHeaderPolicy.You can implement your custom policies if needed. But make sure that your custom policy implementsaiohttp_csrf.policy.AbstractPolicyinterface.StoragesYou can use different types of storages for storing token. Library provides 2 types of storage:CookieStorage. Your token will be stored in cookie variable. You need to specify cookie name.SessionStorage. Your token will be stored in session. You need to specify session variable name.Important:If you want to use session storage, you need setup aiohttp_session in your application
(session storage example)You can implement your custom storages if needed. But make sure that your custom storage implementsaiohttp_csrf.storage.AbstractStorageinterface.Token generatorsYou can use different token generator in your application.
By default storages usingaiohttp_csrf.token_generator.SimpleTokenGeneratorBut if you need more secure token generator - you can useaiohttp_csrf.token_generator.HashedTokenGeneratorAnd you can implement your custom token generators if needed. But make sure that your custom token generator implementsaiohttp_csrf.token_generator.AbstractTokenGeneratorinterface.Invalid token behaviorBy default, if token is invalid,aiohttp_csrfwill raiseaiohttp.web.HTTPForbiddenexception.You have ability to specify your custom error handler. It can be:callable instance. Input parameter - aiohttp request.defcustom_error_handler(request):# do somethingreturnaiohttp.web.Response(status=403)# orasyncdefcustom_async_error_handler(request):# await do somethingreturnaiohttp.web.Response(status=403)It will be called instead of protected handler.sub class of Exception. In this case this Exception will be raised.classCustomException(Exception):passYou can specify custom error handler globally, when initializeaiohttp_csrfin your application:...classCustomException(Exception):pass...aiohttp_csrf.setup(app,policy=csrf_policy,storage=csrf_storage,error_renderer=CustomException)...In this case custom error handler will be applied to all protected handlers.Or you can specify custom error handler locally, for specific handler:...classCustomException(Exception):pass...@aiohttp_csrf.csrf_protect(error_renderer=CustomException)defhandler_with_custom_csrf_error(request):...In this case custom error handler will be applied to this handler only.
For all other handlers will be applied global error handler. |
aiohttp-dashboard | No description available on PyPI. |
aiohttp-datadog | Anaiohttpmiddleware for reporting metrics toDatadog. Python 3.5+ is required.Usagefromaiohttpimportwebfromaiohttp_datadogimportDatadogMiddlewareapp=web.Application(middlewares=(DatadogMiddleware("my_app",{"host":"localhost","port":8126},),),)If you’re using a custom DogStatsd class,
you can supply it via a keyword argument:app=web.Application(middlewares=(DatadogMiddleware("my_app",{"host":"localhost","port":8126},dogstatsd_class=CatStatsd,),),)Or if you’re even more of a control freak,
you can instantiate it yourself:app=web.Application(middlewares=(DatadogMiddleware("my_app",dogstatsd_instance=CatStatsd(meow=False),),),) |
aiohttp-debugmode | aiohttp-debugmodeThis package helps you easily start a aiohttp develpment server in subprocess ,everytime dependencies/statics are modified ,daemon process will automatically reload server thus helps you automation your workflow. Aiohttp-debugtoolbar included.Based on watchdog.Works on Python3.7+aiohttp-debugtoolbarincluded ,thus you can get a full report of traceback if exception raised.(* Screenshot fromaio-libs/aiohttp-debugtoolbar*)Installpip install aiohttp-debugmodeUsagequick_start.py# here's a demo script from aiohttp.doc\quickstartfromaiohttpimportwebroutes=web.RouteTableDef()@routes.get('/')asyncdefhello(request):returnweb.Response(text="Hello, world")app=web.Application()app.add_routes(routes)web.run_app(app)Simply modify severl lines like this# Add importfromaiohttp_debugmodeimportDebugmode# Let Debugmode take over control of run_appDebugmode.run_app(app)By default ,templates&staticfloder is added to observing list of watchdog. You can manually set observe file/floder using append_observe.Debugmode.append_observe(['other/login.html','assets'])If you need some kind of process when a aiohttp server starts up:defstup():...# do somethingDebugmode.on_startup(stup)# accepts callable.Examplesaiohttp-debugmode with VueAssume that you are usiung vue-cli and have a directory structure like this:...
├── Project
│ ├── static
│ ├── templates
│ ├── app.py # aiohttp app entry
│ └── frontend # vue frontend folder
│ ├── dist # webpack output directory
│ │ ├── css
│ │ ├── js
│ │ └── index.html
│ ├── node_modules
│ │ └── ...
│ ├── src # vue source
│ │ └── ...
│ └── vue.config.js
│ └── ...Assume that webpack outputs built file into/Project/frontend/distfloder while your aiohttp app collects templates & statics from/Project/templates&/Project/staticfolder.Here's a sample code:fromaiohttpimportwebfromaiohttp_debugmodeimportDebugmodeimportaiohttp_jinja2# Pretended doing some tempate rander stuff.# @aiohttp_jinja2.template('index.html')asyncdefhello(request):returnweb.Response(text="Randered.")# Debugtoolbar included thus you can get# a full report of traceback.asyncdeferror(request):raiseException('Testing.')app=web.Application()app.router.add_route('GET','/',hello)app.router.add_route('GET','/err',error)app.add_routes([web.static('/','static')])definitialize():importshutil,os,glob# You may use os.path.abspath to get absolute path in some situation.ifos.path.exists('frontend\dist\index.html'):shutil.move('frontend\dist\index.html','templates')try:shutil.rmtree(filepath)os.mkdir(filepath)forfilepathinglob.glob('frontend\dist\*'):shutil.move(filepath,'static')exceptExceptionase:raiseeDebugmode.append_observe(['frontend\dist'])# backslashes on windows.Debugmode.on_startup(initialize)# Debugmode takes over run_app instead of web.run_appDebugmode.run_app(app,host='127.0.0.1',port=8080)Thus every time you runnpm run build,debugmode will catch file modified event ,init file directory and restart aiohttp server with new generated html/js/css file. |
aiohttp-debugtoolbar | aiohttp-debugtoolbaraiohttp_debugtoolbarprovides a debug toolbar for youraiohttpweb application. Library is port ofpyramid_debugtoolbarand
still in early development stages. Basic functionality has been
ported:basic panelsintercept redirectsintercept and pretty print exceptioninteractive python consoleshow source codePorted PanelsHeaderDebugPanel,PerformanceDebugPanel,TracebackPanel,SettingsDebugPanel,MiddlewaresDebugPanel,VersionDebugPanel,RoutesDebugPanel,RequestVarsDebugPanel,LoggingPanelHelp NeededAre you coder looking for a project to contribute to
python/asyncio libraries? This is the project for you!Install and Configuration$ pip install aiohttp_debugtoolbarIn order to plug inaiohttp_debugtoolbar, callaiohttp_debugtoolbar.setupon your app.importaiohttp_debugtoolbarapp=web.Application(loop=loop)aiohttp_debugtoolbar.setup(app)Full Exampleimportasyncioimportjinja2importaiohttp_debugtoolbarimportaiohttp_jinja2fromaiohttpimportweb@aiohttp_jinja2.template('index.html')asyncdefbasic_handler(request):return{'title':'example aiohttp_debugtoolbar!','text':'Hello aiohttp_debugtoolbar!','app':request.app}asyncdefexception_handler(request):raiseNotImplementedErrorasyncdefinit(loop):# add aiohttp_debugtoolbar middleware to you applicationapp=web.Application(loop=loop)# install aiohttp_debugtoolbaraiohttp_debugtoolbar.setup(app)template="""
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<h1>{{ text }}</h1>
<p>
<a href="{{ app.router['exc_example'].url() }}">
Exception example</a>
</p>
</body>
</html>
"""# install jinja2 templatesloader=jinja2.DictLoader({'index.html':template})aiohttp_jinja2.setup(app,loader=loader)# init routes for index page, and page with errorapp.router.add_route('GET','/',basic_handler,name='index')app.router.add_route('GET','/exc',exception_handler,name='exc_example')returnapploop=asyncio.get_event_loop()app=loop.run_until_complete(init(loop))web.run_app(app,host='127.0.0.1',port=9000)Settingsaiohttp_debugtoolbar.setup(app,hosts=['172.19.0.1',])Supported optionsenabled: The debugtoolbar is disabled if False. By default is set to True.intercept_redirects: If True, intercept redirect and display an intermediate page with a link to the redirect page. By default is set to True.hosts: The list of allow hosts. By default is set to [‘127.0.0.1’, ‘::1’].exclude_prefixes: The list of forbidden hosts. By default is set to [].check_host: If False, disable the host check and display debugtoolbar for any host. By default is set to True.max_request_history: The max value for storing requests. By default is set to 100.max_visible_requests: The max value of display requests. By default is set to 10.path_prefix: The prefix of path to debugtoolbar. By default is set to ‘/_debugtoolbar’.Thanks!I’ve borrowed a lot of code from following projects. I highly
recommend to check them out:pyramid_debugtoolbardjango-debug-toolbarflask-debugtoolbarPlay With Demohttps://github.com/aio-libs/aiohttp_debugtoolbar/tree/master/demoRequirementsaiohttpaiohttp_jinja2CHANGES0.6.1 (2023-11-19)Filtered out requests to debugtoolbar itself from the requests history.Improved import time by delaying loading of package data.Fixed static URLs when using yarl 1.9+.Fixed a warning in theremodule.Switched toaiohttp.web.AppKeyfor aiohttp 3.9.Dropped Python 3.7 and added Python 3.11.0.6.0 (2020-01-25)Fixed ClassBasedView support. #207Dropped aiohttp<3.3 support.Dropped Python 3.4 support.Droppedyield [email protected] (2018-02-14)Added safe filter to render_content. #195Added support for aiohtp 3.0.4.1 (2017-08-30)Fixed issue with redirects without location header. #1740.4.0 (2017-05-04)Added asyncio trove classifier.Addes support for aiohttp 2.0.7+.0.3.0 (2016-11-18)Fixed middleware route finding when using sub-apps. #65Added examples for extra panels: pgsql & redis monitor. #590.2.0 (2016-11-08)Refactored test suite.0.1.4 (2016-11-07)Renamed to aiohttp-debugtoolbar.Fixed imcompatibility with aiohttp 1.1.0.1.3 (2016-10-27)Fixed a link to request info page, sort request information alphabetically. #520.1.2 (2016-09-27)Fixed empty functions names in performance panel. #43 (Thanks @kammala!)Fixed flashing message during page rendering issue. #460.1.1 (2016-02-21)Fixed a demo.Added syntax highlight in traceback view, switched highlighter from
highlight.js to prism.js. #310.1.0 (2016-02-13)Added Python 3.5 support. (Thanks @stormandco!)Added view source button in RoutesDebugPanel. (Thanks @stormandco!)Dropped support for Python 3.3. (Thanks @sloria!)Added middleware in setup method. (Thanks @sloria!)Fixed bug with interactive console.Fixed support for aiohttp>=0.21.1.0.0.5 (2015-09-13)Fixed IPv6 socket family error. (Thanks @stormandco!)0.0.4 (2015-09-05)Fixed support for aiohttp>=0.17. (Thanks @himikof!)0.0.3 (2015-07-03)Switched template engine from mako to jinja2. (Thanks @iho!)Added customyield fromto track context switches inside coroutine.Implemented panel for collecting request log messages.Disable toolbar code injecting for non web.Response answers
(StreamResponse or WebSocketResponse for example). #120.0.2 (2015-05-26)Redesigned UI look-and-feel.Renamedtoolbar_middleware_factoryto justmiddleware.0.0.1 (2015-05-18)Initial release. |
aiohttp-deps | AioHTTP depsThis project was initially created to show the abillities oftaskiq-dependenciesproject, which is used bytaskiqto provide you with the best experience of sending distributed tasks.This project addsFastAPI-like dependency injection to yourAioHTTPapplication and swagger documentation based on types.To start using dependency injection, just initialize the injector.fromaiohttpimportwebfromaiohttp_depsimportinitasdeps_initapp=web.Application()app.on_startup.append(deps_init)web.run_app(app)If you use mypy, then we have a custom router with propper types.fromaiohttpimportwebfromaiohttp_depsimportinitasdeps_initfromaiohttp_depsimportRouterrouter=Router()@router.get("/")asyncdefhandler():returnweb.json_response({})app=web.Application()app.router.add_routes(router)app.on_startup.append(deps_init)web.run_app(app)Also, you can nest routers with prefixes,api_router=Router()memes_router=Router()main_router=Router()main_router.add_routes(api_router,prefix="/api")main_router.add_routes(memes_router,prefix="/memes")SwaggerIf you use dependencies in you handlers, we can easily generate swagger for you.
We have some limitations:We don't support resolving type aliases if hint is a string.
If you define variable like this:myvar = int | Noneand then in handler
you'd create annotation like this:param: "str | myvar"it will fail.
You need to unquote type hint in order to get it work.We will try to fix these limitations later.To enable swagger, just add it to your startup.fromaiohttp_depsimportinit,setup_swaggerapp=web.Application()app.on_startup.extend([init,setup_swagger()])ResponsesYou can define schema for responses using dataclasses or
pydantic models. This would not affect handlers in any way,
it's only for documentation purposes, if you want to actually
validate values your handler returns, please write your own wrapper.fromdataclassesimportdataclassfromaiohttpimportwebfrompydanticimportBaseModelfromaiohttp_depsimportRouter,openapi_responserouter=Router()@dataclassclassSuccess:data:strclassUnauthorized(BaseModel):why:[email protected]("/")@openapi_response(200,Success,content_type="application/xml")@openapi_response(200,Success)@openapi_response(401,Unauthorized,description="When token is not correct")asyncdefhandler()->web.Response:...This example illustrates how much you can do with this decorator. You
can have multiple content-types for a single status, or you can have different
possble statuses. This function is pretty simple and if you want to make
your own decorator for your responses, it won't be hard.Default dependenciesBy default this library provides only two injectables.web.Requestandweb.Application.asyncdefhandler(app:web.Application=Depends()):...asyncdefhandler2(request:web.Request=Depends()):...It's super useful, because you can use these dependencies in
any other dependency. Here's a more complex example of how you can use this library.fromaiohttp_depsimportRouter,Dependsfromaiohttpimportwebrouter=Router()asyncdefget_db_session(app:web.Application=Depends()):asyncwithapp[web.AppKey("db")]assess:yieldsessclassMyDAO:def__init__(self,session=Depends(get_db_session)):self.session=sessionasyncdefget_objects(self)->list[object]:returnawaitself.session.execute("SELECT 1")@router.get("/")asyncdefhandler(db_session:MyDAO=Depends()):objs=awaitdb_session.get_objects()returnweb.json_response({"objects":objs})If you do something like this, you would never think about initializing your DAO. You can just inject it and that's it.Built-in dependenciesThis library also provides you with some default dependencies that can help you in building the best web-service.JsonTo parse json, create a pydantic model and add a dependency to your handler.fromaiohttpimportwebfrompydanticimportBaseModelfromaiohttp_depsimportRouter,Json,Dependsrouter=Router()classUserInfo(BaseModel):name:[email protected]("/users")asyncdefnew_data(user:UserInfo=Depends(Json())):returnweb.json_response({"user":user.model_dump()})This dependency automatically validates data and send
errors if the data doesn't orrelate with schema or body is not a valid json.If you want to make this data optional, just mark it as [email protected]("/users")asyncdefnew_data(user:Optional[UserInfo]=Depends(Json())):ifuserisNone:returnweb.json_response({"user":None})returnweb.json_response({"user":user.model_dump()})HeadersYou can get and validate headers usingHeaderdependency.Let's try to build simple example for authorization.fromaiohttp_depsimportRouter,Header,Dependsfromaiohttpimportwebrouter=Router()defdecode_token(authorization:str=Depends(Header()))->str:ifauthorization=="secret":# Let's pretend that here we# decode our token.returnauthorizationraiseweb.HTTPUnauthorized()@router.get("/secret_data")asyncdefnew_data(token:str=Depends(decode_token))->web.Response:returnweb.json_response({"secret":"not a secret"})As you can see, header name to parse is equal to the
name of a parameter that introduces Header dependency.If you want to use some name that is not allowed in python, or just want to have different names, you can use alias. Like this:defdecode_token(auth:str=Depends(Header(alias="Authorization")))->str:Headers can also be parsed to types. If you want a header to be parsed as int, just add the typehint.defdecode_token(meme_id:int=Depends(Header()))->str:If you want to get list of values of one header, use parametermultiple=True.defdecode_token(meme_id:list[int]=Depends(Header(multiple=True)))->str:And, of course, you can provide this dependency with default value if the value from user cannot be parsed for some reason.defdecode_token(meme_id:str=Depends(Header(default="not-a-secret")))->str:QueriesYou can depend onQueryto get and parse query parameters.fromaiohttp_depsimportRouter,Query,Dependsfromaiohttpimportwebrouter=Router()@router.get("/shop")asyncdefshop(item_id:str=Depends(Query()))->web.Response:returnweb.json_response({"id":item_id})the name of the parameter is the same as the name of function parameter.The Query dependency is acually the same as the Header dependency, so everything about theHeaderdependency also applies toQuery.ViewsIf you use views as handlers, please use View class fromaiohttp_deps, otherwise the magic won't work.fromaiohttp_depsimportRouter,View,Dependsfromaiohttpimportwebrouter=Router()@router.view("/view")classMyView(View):asyncdefget(self,app:web.Application=Depends()):returnweb.json_response({"app":str(app)})FormsNow you can easiy get and validate form data from your request.
To make the magic happen, please addarbitrary_types_allowedto the config of your model.importpydanticfromaiohttp_depsimportRouter,Depends,Formfromaiohttpimportwebrouter=Router()classMyForm(pydantic.BaseModel):id:intfile:web.FileFieldmodel_config=pydantic.ConfigDict(arbitrary_types_allowed=True)@router.post("/")asyncdefhandler(my_form:MyForm=Depends(Form())):withopen("my_file","wb")asf:f.write(my_form.file.file.read())returnweb.json_response({"id":my_form.id})PathIf you have path variables, you can also inject them in your handler.fromaiohttp_depsimportRouter,Path,Dependsfromaiohttpimportwebrouter=Router()@router.get("/view/{var}")asyncdefmy_handler(var:str=Depends(Path())):returnweb.json_response({"var":var})Overridiing dependenciesSometimes for tests you don't want to calculate actual functions
and you want to pass another functions instead.To do so, you can add "dependency_overrides" or "values_overrides" to the aplication's state.
These values should be dicts. The keys for these values can be found inaiohttp_deps.keysmodule.Here's an example.deforiginal_dep()->int:return1classMyView(View):asyncdefget(self,num:int=Depends(original_dep)):"""Nothing."""returnweb.json_response({"request":num})Imagine you have a handler that depends on some function,
but instead of1you want to have2in your tests.To do it, jsut adddependency_overridessomewhere,
where you create your application. And make sure that keys
of that dict are actual function that are being replaced.fromaiohttp_depsimportVALUES_OVERRIDES_KEYmy_app[VALUES_OVERRIDES_KEY]={original_dep:2}Butvalues_overridesonly overrides returned values. If you want to
override functions, you have to usedependency_overrides. Here's an example:fromaiohttp_depsimportDEPENDENCY_OVERRIDES_KEYdefreplacing_function()->int:return2my_app[DEPENDENCY_OVERRIDES_KEY]={original_dep:replacing_function}The cool point aboutdependency_overrides, is that it recalculates graph and
you can use dependencies in function that replaces the original. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.