Saravanan666/pypi-org huggingface dataset:
Package: asyncfile
A simple and up-to-date module that enables compatibility with asyncio and fileIO operations in Python.PurposeOperating on files in Python is a synchronous activity. When normally operating on file this does not
cause any problems. However, when files are tampered with in code that also runs the asyncio event
loop, this can cause theasyncioevent loopto block. This negatively effects the program’s performance
and should therefore be avoided. Theasyncfilemodule avoids this problem by running the file operations in a separate
thread so that the event loop is not as harshly affected.Featuresasyncandawaitsyntax is usedThere is almost complete coverage of theiomodule’s classesThe syntax and utility is similar to the built-in Pythonopenfunction and the built-iniomoduleLightweight in speed and memoryInstallationInstallingasyncfileshould be done throughPIP:pipinstallasyncfileOpen ExamplesIf you were to have regular, blocking code, you can easily transition it toasyncfileBlocking:withopen('fake_file','r')asf:print(f.read())Non-Blocking:importasyncfileimportasynciocustom_loop=asyncio.get_event_loop()# You can pass in your own loopasyncdefopen_file():asyncwithasyncfile.open('fake_file','r',loop=custom_loop)asf:print(awaitf.read())custom_loop.run_until_complete(open_file())These both produce the same results, but one is better suited for asyncio-based code.IO ExamplesBlocking:importiowrap=io.FileIO('fake_file.txt','wb')buff=io.BufferedReader(wrap)buff.write(b'Random bytes')print(buff.fileno())print(buff.raw)print(buff.readable())buff.close()Non-Blocking:importasyncfileimportasyncioasyncdefno_block(file_path):wrap=asyncfile.AsyncFileIO(file_path,'rb')buff=asyncfile.AsyncBufferedReader(wrap)awaitbuff.read(-1)print(awaitbuff.fileno())print(buff.raw)print(awaitbuff.readable())awaitbuff.close()loop=asyncio.get_event_loop()loop.run_until_complete(no_block('fake_file.txt'))Blocking:importioforiinio.FileIO('fake_file.txt'):print(i)Non-Blocking:importasyncfileimportasyncioasyncdefasync_iteration():asyncforiinasyncfile.AsyncFileIO('fake_file.txt'):print(i)
Package: async-files
async-filesasync-files is a fast, lightweight, and extensible asyncio file library, written in pure python and inspired byaiofiles. This works just like aiofiles which delegates file IO operations to a separate thread pool. Although, async-files have been completely re-written from scratch to use modernasync...await...syntax and with extensibility and flexibility in mind.UsageFiles can be opened with async context manager or by calling FileIO instance.asyncwithFileIO("README.md")asf:s=awaitf.read()print(s)orf=awaitFileIO("README.md")()# __init__ can't be asynchronous.s=awaitf.read()print(s)awaitf.close()Asynchronous iteration is also supported.asyncwithFileIO("README.md")asf:asyncforlineinf:print(line,end="")You can also extend functionality of FileIO to support other classes liketempfile.TemporaryFilevery easily:fromtempfileimportTemporaryFileas_TemporaryFilefromasync_filesimportFileIOclassTemporaryFile(FileIO):OPEN=_TemporaryFileYou can do same for any other IO classes likegzip.GzipFile,zipfile.ZipFile, etc.
I have added async version of tempfile and gzip modules in thev0.2since they are commonly used modules and I will add more modules in the future releases.
You can use these modules just like you use standard library module, only difference is you need to await coroutine methods.
You can request for support for new modules bycreating new issue.You can also create coroutine from any blocking function by using async-files's utility functionasync_wraps. For example:importshutilfromasync_files.utilsimportasync_wrapsasync_rmtree=async_wraps(shutil.rmtree)You can also useasync_wrapsas a decorator for your custom function.Note: Only useasync_wrapsif target function is IO-bound.Following are asynchronous attributes of the FileIO object.close:Callable[[],Awaitable[None]]flush:Callable[[],Awaitable[None]]isatty:Callable[[],Awaitable[bool]]read:Callable[[],Awaitable[Union[str,bytes]]]read1:Callable[[],Awaitable[bytes]]readinto:Callable[[bytearray],Awaitable[int]]readinto1:Callable[[bytearray],Awaitable[int]]readline:Callable[[],Awaitable[Union[str,bytes]]]readlines:Callable[[],Awaitable[List[Union[str,bytes]]]]seek:Callable[[],Awaitable[int]]tell:Callable[[],Awaitable[int]]truncate:Callable[[],Awaitable[int]]write:Callable[[Union[str,bytes]],Awaitable[int]]writelines:Callable[[List[Union[str,bytes]]],Awaitable[None]]Other attributes are synchronous just like standard library fileobj.Feedback & ContributionsBugs and feature requests can be made viaGitHub issues.
Be aware that these issues are not private, so take care when providing output to make sure you are not disclosing security issues in other products.Pull requests are also welcome via git.The async-files usessourcery,restyledandcode factorbots to ensure code quality of the PR.
Package: async-fivem
async-fivemAsynchronous FiveM package for retrieving Player and Server infos utilizing theaiohttppackage.UsageimportasynciofromfivemimportFiveMip="127.0.0.1"port=30120asyncdefmain():fivem=FiveM(ip=ip,port=port)# raw list of players like you get from /players.jsonplayers=awaitfivem.get_players_raw()# raw json of server-info like you get from /info.jsoninfo=awaitfivem.get_info_raw()# raw json of server-info like you get from /dynamic.jsondynamic=awaitfivem.get_dynamic_raw()# parsed list of Player objectsplayers=awaitfivem.get_players()# parsed Server objectserver=awaitfivem.get_server_info()loop=asyncio.get_event_loop()loop.run_until_complete(main())Api ReferenceFiveMclassFiveM(ip:str, port:int):await get_players_raw()-> list:/players.json endpoint - raw list of playersawait get_info_raw()-> dict:/info.json endpoint - raw dict with server-infoawait get_dynamic_raw()-> dict:/dynamic.json endpoint - raw dict with server-infoawait get_players()-> [Player]:returns parsed list ofPlayerobjectsawait get_server_info()->Server:returns parsed server infoServerPlayerclassPlayer:name:player usernameid:player idping:current player pingxbl_id:xbl id, None if not availablesteam_id:steam id, None if not availablediscord_id:discord id, None if not availablelive_id:live id, None if not availablelicense_id:license id, None if not availableServerclassServer:hostname:servers hostnameclients:current number of clientsmax_clients:max clients allowed on servergame_type:servers game typemap_name:servers map nameRequirementsPython >= 3.6aiohttpIssues and FeaturesIf you're having any issues or want additional features please create an Issue ongithub.
Package: asyncfix
AsyncFIX - AsyncIO FIX Protocol Python FrameworkAsyncIO FIX protocol library for PythonHighlightsPythonic way of dealing with FIX messagesSchema validationTools for unit testing client appsNewOrderSingle container / state management supportSession management included (FIX journaling, session restoring, heartbeats, resets)FIX Tester - tool for FIX unit testing (schema validation, order management, protocol
message exchange)FIX 4.4 protocol implemented100% unit test code coverageInstallationpip install asyncfixGetting startedSimple snippetsClient exampleFull DocumentationCreditsThis project initially intended to be a fork ofAIOPyFIX,
but things went too deep and too far. Hopefully, this project could help. Please, star this repo
if you are going to use this project.LicenseMIT 2023 Aleksandr Vedeneev
Package: async-fm
AsyncFMPython library for interacting with the Last.fm API asynchronously.Installationpipinstallasync-fmUsageFirst, you need to obtain an API key and secret from Last.fm. You can do this by creating an account on theirdeveloper site.importasyncioimportasyncfmlastfm=asyncfm.LastFMAPI(api_key="api_key_here")asyncdefmain():# Get the recent tracks for a usertracks=awaitlastfm.user.get_recent_tracks(username="rj")fortrackintracks.data:print(f" ~{track.artist}-{track.title}: image{track.images.extralarge}")print(f"Total:{tracks.total}")asyncio.run(main())RequirementsaiohttppydanticCode FormattingThe code in this repository is formatted usingBlack. You can format the code in your local copy of the repository using:ContributingContributions are welcome! Please open an issue or submit a pull request if you encounter a bug or would like to make an improvement.TestingWe currently don't have any tests for this library, but we'd love your help in adding some! If you're interested in contributing, here's what you can do:Fork the repoInstall the dependencies by running:poetry install.Write your tests intestsdirectoryRun the tests with pytestSubmit a pull request with your changesThanks for considering contributing tests to this library!LicenseThis project is licensed under the terms of the MIT license. See the LICENSE file for more information.
Package: async-foaas
async_foaasA simple Async Python library toFOAAS.Author:Alex RaskinVersion: 0.3.0License:MITDocumentationInstallationThis package relies onhttpx,async-propertyand should be installed withpip:pipinstallasync_foaasBasic UsageFuck off:fromasync_foaasimportFuckimportasynciofuck=Fuck(secure=True)asyncdefmain():fuck_off=awaitfuck.off(name='Tom',from_='Chris').textprint(fuck_off)asyncio.run(main())Give me some fucking JSON:print(awaitfuck.that(from_='Chris').json){u'message':u'Fuck that.',u'subtitle':u'- Chris'}Just get the fucking URL:print(fuck.everything(from_='Chris').url)http://foaas.dev/everything/ChrisGive me some random fucking things:print(awaitfuck.random(from_='Chris').text)Fuckyouverymuch.-Chrisprint(awaitfuck.random(from_='Chris').text)Fuckmylife.-Chrisprint(awaitfuck.random(name='Tom',from_='Chris').text)Fuckmegentlywithachainsaw,Tom.DoIlooklikeMotherTeresa?-Chrisprint(awaitfuck.random(name='Tom',from_='Chris').text)Fuckoff,Tom.-ChrisSupported Actionsfuck.awesome(from_)fuck.ballmer(name, company, from_)fuck.because(from_)fuck.bus(name, from_)fuck.bye(from_)fuck.caniuse(namer, from_)fuck.chainsaw(name, from_)fuck.cool(from_)fuck.diabetes(from_)fuck.donut(name, from_)fuck.everyone(from_)fuck.everything(from_)fuck.fascinating(from_)fuck.field(name, from_, reference)fuck.flying(from_)fuck.king(name, from_)fuck.life(from_)fuck.linus(name, from_)fuck.madison(name, from_)fuck.nugget(name, from_)fuck.off(name, from_)fuck.outside(name, from_)fuck.pink(from_)fuck.thanks(from_)fuck.that(from_)fuck.thing(thing, from_)fuck.this(from_)fuck.random(name, from_)fuck.shakespeare(name, from_)fuck.what(from_)fuck.xmas(name, from_)fuck.yoda(name, from_)fuck.you(name, from_)tl;drfoaas.Fuck([secure=True]).<action>(**kwargs)[.<url|html|text|json>]Testing$pythontests.py.......----------------------------------------------------------------------Ran7testsin0.724sOK
Package: asyncforismatic
ForismaticAn unoficall library for getting quotes from the Forismatic API. Supports asynchronous syntax.Неофицальная библиотека для получения цитат из Forismatic API. Поддерживает асинхронный синтаксис.Installing || Установкаpip3installasyncforismaticRequires aiohttp and requestsExamples || Примерыimportasyncforismaticimportasyncio# getting sync quote on russian as dict# синхронное получение цитаты на русском в виде словаряprint(asyncforismatic.quote(lang='ru',as_dict=True))# getting async quote with default params (english language and formated quote)# асинхронное получение цитаты со стандартными параметрами (английский язык и отформатированная цитата)asyncdefexample():returnawaitasyncforismatic.asyncforismatic()print(asyncio.run(example()))Methods || МетодыGetting a quote (async) || Получение цитаты (асинхронно)corotinueasyncforismatic(lang='en', *, as_dict=False)Returns an quote from Forismatic APIВозвращает цитату из Forismatic APIParameters || Параметрыas_dict:boolIf True, quote returns as JSON-like object (dict)Если True, возвращает результат в JSON'о подобном формате (dict, словарь)Raises exceptions || Поднимает исключенияTypeErrorThe language is not passed as 'str'Язык передан не как 'str'LangIsNotSupportedThe language is not supportedЯзык не поддерживаетсяReturnsUnion[str, dict]ВозвращаетUnion[str, dict]Getting a quote || Получение цитатыdefquote(lang='en', *, as_dict=False)Returns an quote from Forismatic APIВозвращает цитату из Forismatic APIParameters || Параметрыas_dict:boolIf True, quote returns as JSON-like object (dict)Если True, возвращает результат в JSON'о подобном формате (dict, словарь)Raises exceptions || Поднимает исключенияTypeErrorThe language is not passed as 'str'Язык передан не как 'str'LangIsNotSupportedThe language is not supportedЯзык не поддерживаетсяReturnsUnion[str, dict]ВозвращаетUnion[str, dict]Exceptions || ИсключенияLangIsNotSupportedRaises when the language is not supportedВозникает когда язык не поддерживается
Package: async_freesia
![freesia](./images/logo.png)## IntroductionFreesia is a concise and lightweight async web framework. Its api is inspired by Flask.## Installation```bashpip install async-freesia```## DocsYou can find the project's detailed API documentation on [here](https://freesia.readthedocs.io/en/latest/?).## Example*hello world*```pythonfrom freesia import Freesiaapp = Freesia()@app.route('/hello/<name>')async def hello(request, name):return "Hello, " + name + "!"if __name__ == "__main__":app.run()```*middleware*```pythonfrom freesia import Freesiaapp = Freesia()@app.route("/<name>")async def hello(request, name):print("enter user handler")return "hello, " + nameasync def middleware1(request, handler):print("enter middleware1")res = await handler()print("exit middleware1")return res + " !"async def middleware2(request, handler):print("enter middleware2")res = await handler()print("exit middleware2")return res + " :D"app.use([middleware1, middleware2])if __name__ == "__main__":app.run()```*session*```pythonfrom freesia import Freesia, set_up_session, get_session, Responsefrom freesia.session import SimpleCookieSessionapp = Freesia()@app.route("/")async def hello(request):s = await get_session(request)if "count" not in s:s["count"] = 1return Response(text="Hello, stranger!")else:s["count"] += 1return Response(text="I've seen you %d times" % s["count"])if __name__ == "__main__":set_up_session(app, SimpleCookieSession)app.run()```## MoreYou can see more exmaple and usags in [docs](https://freesia.readthedocs.io/en/latest/?) and [examples](./examples).
Package: async-fsm
Async FSMA finite state machine implementation with asyncioFree software: Apache Software License 2.0Documentation:https://async-fsm.readthedocs.io.FeaturesTODOCreditsThis package was created withCookiecutterand theaudreyr/cookiecutter-pypackageproject template.History0.1.0 (2019-05-20)First release on PyPI.
Package: asyncgelf
AsyncGELFAsync python logging handlers that send messages in the Graylog Extended Log Format (GELF).AsyncGELFList of ready to run GELF handlersGet AsyncGELFUsageGELF TCPGELF HTTPGELF UDPAdditional fieldAvailable paramsList of ready to run GELF handlersTCP (with and without TLS);HTTP (with and without TLS);UDP;Get AsyncGELFpipinstallasyncgelfUsageGELF TCPimportasyncioimportasyncgelfasyncdefmain(message):handler=asyncgelf.GelfTcp(host='127.0.0.1',)awaithandler.tcp_handler(message)asyncio.run(main(message))GELF TCP with custom timestampimportasyncioimportasyncgelffromdatetimeimportdatetimeasyncdefmain(message):handler=asyncgelf.GelfTcp(host='127.0.0.1',)event_time="2024-02-06 08:25:56.789"timeformat="%Y-%m-%d%H:%M:%S.%f"awaithandler.tcp_handler(message,datetime.strptime(event_time,timeformat).timestamp())asyncio.run(main(message))GELF HTTPimportasyncioimportasyncgelfasyncdefmain(message):handler=asyncgelf.GelfHttp(host='127.0.0.1',)awaithandler.http_handler(message)asyncio.run(main(message))GELF UDPimportasyncioimportasyncgelfasyncdefmain(message):handler=asyncgelf.GelfUdp(host='127.0.0.1',)awaithandler.udp_handler(message)asyncio.run(main(message))Additional fieldExpect Dict with the following moments:All keys must start with underscore (_) prefix;_idcan't be an additional field;Allowed characters in field names are any word character (letter, number, underscore), dashes and dotsimportasyncioimportasyncgelfasyncdefmain(message):additional_field={'_key_1':'value_1','_key_2':'value_2',}handler=asyncgelf.GelfTcp(host='127.0.0.1',additional_field=additional_field)awaithandler.tcp_handler(message)asyncio.run(main(message))Available paramshostRequired | Graylog server address;portOptional | Graylog input port (default: 12201);gelf_versionOptional | GELF spec version (default: 1.1)levelOptional | The level equals to the standard syslog levels (default: 1);schemeOptional | HTTP Schemefor GELF HTTP input only(default: http);tlsOptional | Path to custom (self-signed) certificate in pem format (default: None)compressOptional | Compress message before sending it to the server or not (default: False)compress_levelOptional | Set compression level: available from 1 (BEST_SPEED) to 9 (BEST_COMPRESSION) (default: 1)debugOptional | Additional information in error log (default: False)additional_fieldOptional | Dictionary with additional fields which will be added to every gelf message (default: None)dns_resolveOptional | Variable host will be checked to existing DNS as parameter and if dns is found, then on initialization will resolve to ip and variable will be updated. By default, UDP handler gets resolved by DNS on every log message. See more:#91305(default: False)
Package: async_generator
The async_generator libraryPython 3.6 addedasync generators. (What’s an async
generator?Check out my 5-minute lightning talk demo from PyCon 2016.) Python 3.7 adds some more
tools to make them usable, likecontextlib.asynccontextmanager.This library gives you all that back to Python 3.5.For example, this code only works in Python 3.6+:asyncdefload_json_lines(stream_reader):asyncforlineinstream_reader:yieldjson.loads(line)But this code does the same thing, and works on Python 3.5+:fromasync_generatorimportasync_generator,yield_@async_generatorasyncdefload_json_lines(stream_reader):asyncforlineinstream_reader:awaityield_(json.loads(line))Or in Python 3.7, you can write:fromcontextlibimportasynccontextmanager@asynccontextmanagerasyncdefbackground_server():asyncwithtrio.open_nursery()asnursery:value=awaitnursery.start(my_server)try:yieldvaluefinally:# Kill the server when the scope exitsnursery.cancel_scope.cancel()This is the same, but back to 3.5:fromasync_generatorimportasync_generator,yield_,asynccontextmanager@asynccontextmanager@async_generatorasyncdefbackground_server():asyncwithtrio.open_nursery()asnursery:value=awaitnursery.start(my_server)try:awaityield_(value)finally:# Kill the server when the scope exitsnursery.cancel_scope.cancel()(And if you’re on 3.6, you can use@asynccontextmanagerwith
native generators.)Let’s do thisInstall:python3-mpip install-Uasync_generator(or on Windows,
maybepy-3-mpip install-Uasync_generatorManual:https://async-generator.readthedocs.io/Bug tracker and source code:https://github.com/python-trio/async_generatorReal-time chat:https://gitter.im/python-trio/generalLicense: MIT or Apache 2, your choiceContributor guide:https://trio.readthedocs.io/en/latest/contributing.htmlCode of conduct: Contributors are requested to follow ourcode of
conductin
all project spaces.How come some of those links talk about “trio”?Triois a new async concurrency
library for Python that’s obsessed with usability and correctness – we
want to make iteasyto get thingsright. Theasync_generatorlibrary is maintained by the Trio project as part of that mission, and
because Trio usesasync_generatorinternally.You can useasync_generatorwith any async library. It works great
withasyncio, or Twisted, or whatever you like. (But we think Trio
is pretty sweet.)
Package: async-gfycat
Async GfycatAn async Python wrapper for theGfycat API.based onpy-gfycata sync wrapper
(api endpoints of py-gfycat are outdated as of 0.2.2)Installationpipinstall-Uasync-gfycatGfycat API KeyGo tohttps://developers.gfycat.com/signup/#/apiformand sign up for an API key if you don't already have one.You need the Client ID and Client Secret to use for initializing the Python client.Getting Startedfromasync_gfycat.clientimportGfycatClientclient=GfycatClient(clientid,secret)# Example requestawaitclient.upload_from_file('willsmith.gif',title='willsmith slap')you can also use username and password authentication withclient=GfycatClient(clientid,secret,username,password)Error HandlingGfycatClientError - General error handler, access message and status code and the response dict withfromgfycat.errorimportGfycatClientErrorfrompprintimportpprinttry...exceptGfycatClientErroraseprint(e.error_message)print(e.status_code)pprint(e.response_data)GfycatClient Class MethodsUploadsupload_from_url(url)upload_from_file(filepath)Warning: usingcheck_upload()immediately after uploading a file may
result in a NotFoundo response, in that case waiting a moment will fix the issue, this is an api issue not a client oneQuery a GFY for URLs and more informationquery_gfy(gfyname)Check if an upload has been convertedcheck_upload(link)all methods return coros and need to be awaited
Package: asyncgnostic
asyncgnosticPython functions agnostic towards being called with await or otherwise.Usesmultiple dispatchto automatically call asynchronous or synchronous function based on calling context.Example:Automatic sync/async dispatchimportasynciofromasyncgnosticimportawaitable# Define a sync functiondefhandler()->str:# type: ignorereturn"Running Sync"# Pair the sync function with an async function@awaitable(handler)asyncdefhandler()->str:return"Running Async"# Call the function from sync contextdefsync_main():print("sync context:",handler())# Call the function from async contextasyncdefasync_main():print("async context:",awaithandler())# Run the sync and async functionssync_main()asyncio.run(async_main())Output:sync context: Running Syncasync context: Running AsyncDetect context in your function for sync/async dispatch dispatchimportasynciofromasyncgnosticimportawaited# Define a sync functiondefsync_handler()->str:# type: ignorereturn"Running Sync"# Define an async functionasyncdefasync_handler()->str:return"Running Async"# Define a dispatcherdefhandler()->str:ifawaited():# If called from async context, call async functionreturnasync_handler()else:# If called from sync context, call sync functionreturnsync_handler()# Call the function from sync contextdefsync_main():print("sync context",handler())# Call the function from async contextasyncdefasync_main():print("async context:",awaithandler())# Run the sync and async functionssync_main()asyncio.run(async_main())Output:sync context: Running Syncasync context: Running AsyncInstallpip install asyncgnosticCredits:Gratefully borrowed improvements fromcurio.Reference:https://mastodon.sharma.io/@harshad/110476942596328864https://mastodon.social/@dabeaz/110477080111974062https://github.com/dabeaz/curio/blob/master/curio/meta.py
Package: async-google-trans-new
async_google_trans_newThis is a library based ongoogle_trans_newbut it is async!It's very easy to use and solve the problem that the old api which use tk value cannot be used.This interface is for academic use only, please do not use it for commercial use.InstallationRun this:pipinstallasync-google-trans-newBasic UsageTranslateimportasyncioimportasync_google_trans_newasyncdefcoro():g=async_google_trans_new.AsyncTranslator()print(awaitg.translate("こんにちは、世界！","en"))loop=asyncio.get_event_loop()loop.run_until_complete(coro())->Helloworld!Advanced UsageTranslateMulti Translateimportasynciofromasync_google_trans_newimportAsyncTranslatorasyncdefcoro():g=AsyncTranslator()texts=["こんにちは、世界！","こんばんは、世界！","おはよう、世界！"]gathers=[]fortextintexts:gathers.append(g.translate(text,"en"))print(awaitasyncio.gather(*gathers))loop=asyncio.get_event_loop()loop.run_until_complete(coro())->['Hello World! ','Good evening, the world! ','Good morning, the world! ']PrerequisitesPython 3.8 (Please make GitHub issue if you can use this lib on different python version)aiohttpurllib3LicensePlease seeLICENSE.