Saravanan666/pypi-org huggingface dataset:
Package: async-notify
Async-NotifyAsync-Notify is a simple, asyncio-based notification library for Apps.Notify is built on top of python asyncio for send notifications asynchronous with support of twilio, telegram, o365, email, slack, onesignal and many others.Why Async-Notify?The finality of Async-Notify is to provide us a subset of communication providers for sending different notifications in a non-blocking mode..
The main goal of Async-Notify is using only asyncio-based technologies.RequirementsPython >= 3.8asyncio (https://pypi.python.org/pypi/asyncio/)Quick TutorialCurrently Async-Notify supports the following providers:Amazon SESEmail (SMTP)GmailOffice 365Telegram (requires aiogram)Twilio (SMS)OneSignalTwitterXMPP stanzasFuture work:SlackFacebook MessengerDiscordIRCHow do I get set up?Summary of set upConfigurationDependenciesDatabase configurationHow to run testsDeployment instructionsContribution guidelinesPlease have a look at the Contribution GuideWriting testsCode reviewWho do I talk to?Repo owner or adminOther community or team contactLicenseAsync-Notify is copyright of Jesus Lara (https://phenobarbital.info) and is licensed under BSD license. I am providing code in this repository under an open source licenses, remember, this is my personal repository; the license that you receive is from me and not from my employeer.
Package: asyncns
Welcome toasyncns!Useful LinksGitHubpypiThe DocsFAQs:What isasyncns?asyncnsis an asynchronous API wrapper forNationStates.Why isasyncnsuseful?asyncnsis useful for:Applications that need to make API calls to NationStates, but don't want to block the main thread.That's about it, really.This is not a library that's helpful for much. It's just a wrapper for NationStates.Should I useasyncns?I guess. If you need to make async requests, there aren't that many options out there other than writing your own.What dependencies doesasyncnshave?aiohttp
Package: asyncnt
AsyncNTAn asynchronous way to fetch data fromnitrotype.FeaturesAsyncio supportAccess to the Nitro Type APIRate limit of 10 requests per secondCache to speed up requestsInstallationpip install asyncntBasic Usageimportasyncioimportasyncntasyncdefmain():#create a sessionasyncwithasyncnt.Session()assession:#get a Racer objectracer=awaitsession.get_racer("travis")#print races the racer hasprint(racer.races)#get a Team objectteam=awaitsession.get_team("NT")#print team's daily speedprint(team.daily_speed)Check out thedocsfor more information.LisenceMIT
Package: asyncodbc
asyncodbcis a Python 3.5+ module that makes it possible to accessODBCdatabases
withasyncio. It relies on the awesomepyodbclibrary and preserves the same look and
feel.asyncodbcwas written usingasync/awaitsyntax (PEP492) and thus is not compatible
with Python versions older than 3.5.  Internallyasyncodbcemploys threads to avoid
blocking the event loop,threadsare not that as bad as you think!. Other
drivers likemotoruse the same approach.asyncodbcis fully compatible and tested withuvloop. Take a look at the test
suite, all tests are executed with both the default event loop anduvloop.Supported Databasesasyncodbcshould work with all databases supported bypyodbc. But for now the
library has been tested with:SQLite,MySQLandPostgreSQL. Feel
free to add other databases to the test suite by submitting a PR.Basic Exampleasyncodbcis based onpyodbcand provides the same api, you just need
to useyield from conn.f()orawait conn.f()instead ofconn.f()Properties are unchanged, soconn.propis correct as well asconn.prop = val.importasyncioimportasyncodbcloop=asyncio.get_event_loop()asyncdeftest_example():dsn='Driver=SQLite;Database=sqlite.db'conn=awaitasyncodbc.connect(dsn=dsn,loop=loop)cur=awaitconn.cursor()awaitcur.execute("SELECT 42 AS age;")rows=awaitcur.fetchall()print(rows)print(rows[0])print(rows[0].age)awaitcur.close()awaitconn.close()loop.run_until_complete(test_example())Connection PoolConnection pooling is ported fromaiopgand relies onPEP492features:importasyncioimportasyncodbcloop=asyncio.get_event_loop()asyncdeftest_pool():dsn='Driver=SQLite;Database=sqlite.db'pool=awaitasyncodbc.create_pool(dsn=dsn,loop=loop)asyncwithpool.acquire()asconn:cur=awaitconn.cursor()awaitcur.execute("SELECT 42;")r=awaitcur.fetchall()print(r)awaitcur.close()awaitconn.close()pool.close()awaitpool.wait_closed()loop.run_until_complete(test_pool())Context ManagersPool,ConnectionandCursorobjects support the context management
protocol:importasyncioimportasyncodbcloop=asyncio.get_event_loop()asyncdeftest_example():dsn='Driver=SQLite;Database=sqlite.db'asyncwithasyncodbc.create_pool(dsn=dsn,loop=loop)aspool:asyncwithpool.acquire()asconn:asyncwithconn.cursor()ascur:awaitcur.execute('SELECT 42 AS age;')val=awaitcur.fetchone()print(val)print(val.age)loop.run_until_complete(test_example())InstallationIn a linux environmentpyodbc(henceasyncodbc) requires theunixODBClibrary.
You can install it using your package manager, for example:$ sudo apt-get install unixodbc
$ sudo apt-get install unixodbc-devthen:pip install asyncodbcRun testsFor testing purposes you need to installdockerand the development
requirements:$ pip install -r requirements-dev.txtIn order to simplify development you should install the provided docker container.
This way you don’t need to install any databases or other system libraries, everything happens inside the container.Then just execute:$ make docker_build
$ make docker_testThe test will automatically pull images and build containers with
the required databases.NOTE:Running tests requires Python 3.6 or higher.Other SQL Driversaiopg- asyncio client for PostgreSQLaiomysql- asyncio client form MySQLRequirementsPython3.5+pyodbcuvloop(optional)
Package: asyncode
asyncodePython package for emulating Python's interactive interpreter in asynchronous contexts.InstallationUse the package managerpipto install asyncode:pipinstallasyncodeDependenciesPython≥ 3.5(no CI for Python < 3.8)UsageThis package's external API consists in two classes,AsyncInteractiveInterpreterandAsyncInteractiveConsole, which subclass respectivelycode.InteractiveInterpreterandcode.InteractiveConsole.These classes are meant to be used inalready running asynchronous contexts. Minimal useful code will need to subclass provided classes to implement specific functions:importasyncodeclassMyAsyncConsole(asyncode.AsyncInteractiveConsole):"""AsyncInteractiveConsole adapted to running environment"""asyncdefwrite(self,data):"""Use specific function"""awaitsome_output_coroutine(data)asyncdefraw_input(self,prompt=""):"""Use specific functions"""ifprompt:awaitsome_output_coroutine(prompt)data=awaitsome_input_coroutine()returndataasyncdefrun_interpreter():"""Run an interactive Python interpreter"""console=MyAsyncConsole()try:awaitconsole.interact()exceptSystemExit:# Do not exit the whole program when sending "exit()" or "quit()"awaitsome_output_coroutine("Bye!")Readthe docsfor more informations.ContributingPull requests are welcome. Do not hesitate to get in touch with me (see below) for any question or suggestion about this project!LicenseThis work is shared underthe MIT license.© 2020 Loïc Simon (loic.simon@espci.org)
Package: asyncoinpayments
AsynCoinpaymentsAn async/await compatible python wrapper for the CoinPayments APIHow to install# run this in the command propt or terminal
pip install asyncoinpaymentsFeaturesFast to setup and simple to useEasy to use async/await interfaceAPI calls using aiohttp requestscreate your own API callsContact meEmail:flalugli.dev@gmail.comDiscord: flalugli
Package: async-okta-jwt
Async Okta JwtAsync Okta JWT Access Token verifier for Python using cached JWKs.Based onokta_jwtby Adithya SampatoorLink to PyPi - clickhereInstallationpipinstallasync_okta_jwtUsageTo generate a token, you need to pass inissuer,client_id,client_secret,usernameandpasswordas parameters>>>fromasync_okta_jwt.jwtimportgenerate_token>>>awaitgenerate_token(issuer,client_id,client_secret,username,password)This generates and returns Okta Access Token.To Validate the Access Token, you need to pass in theaccess_token,issuer,audienceandclient_idsas parameters. You can pass in multiple Client IDs>>>fromasync_okta_jwt.jwtimportvalidate_token>>>awaitvalidate_token(access_token,issuer,audience,client_ids)If the token is valid then it will return the payload.Running the testsTo run the unit tests, run$ python -m unittestBreak down into testsThe unit tests pretty much covers all the main functionality of the package, like generating the token, Validating the token and Verifying Claims.ContributingBug reports and Pull Requests(PR's) are welcome on GitHub athttps://github.com/ypukhta/async_okta_jwt. This project is intended to be a safe, welcoming
space for collaboration, and contributors are expected to adhere to theContributor Covenantcode of conduct.AuthorsAdithya SampatoorYevgen PukhtaLicenseThe Library is available as open source under the terms of theMIT License
Package: asyncom
AsyncOMAsync OM it's a super basic Object mapper based almost all on sqlalchemy
ORM layer.We use the declarative extension for building the classes, and also,
factor instances of them on querys. (*Limited support)There is still no support for relations.Depens onencode/databasesdependency.MotivationI don't like the asyncpgsa approach where they are just using,
the core layer, to build run the sqlgenerator. I like to build,
around the declarative layer of sqlachemy, and later found that
I can patch some of the methods on the session.query, to
use it's own sql generator, and turn async the query system.Object persistent is minimal, and needs some love.Usagefromsqlalchemy.ext.declarativeimportdeclarative_baseimportsqlalchemyassafromdatabasesimportDatabaseURLBase=declarative_base()classOrmTest(Base):__tablename__='orm_test'id=sa.Column(sa.Integer,primary_key=True)name=sa.Column(sa.String(100),index=True)value=sa.Column(sa.Text)# Instead of usign Database from databases, you can use:db=OMDatabase(DatabaseURL('postgres://root@postgres:{port}/guillotina'))# instances of the object can be created with:test=OrmTest(name='xx',value='yy')awaitdb.add(test)print(test.id)# pk column is correct set# get an instanceins=awaitdb.query(OrmTest).get(1)total=awaitdb.query(OrmTest).count()asserttotal==1# remove itawaitdb.delete(ins)# filter themres=awaitdb.query(OrmTest).filter(OrmTest.name.like('xx')).all()# Or just iterate over the results with a cursor:asyncforrowindb.query(OrmTest).filter(OrmTest.name.like('xx')):print(f'Row{row.name}:{row.value}')# There is basic support for table inheritance query OneToOne# Look at testsChangelog0.3.3Fix collections import for Python 3.100.3.2Support query multiple primary keys0.3.1Be able to provide mapper_factory toOMQuery[vangheem]0.3.0Fix bug with om.delete an inherited objects0.2.3Fix boolean expr on adding prods.
Allowing to add values with 00.2.1Small fix when checking none on json fields arrays0.1.9Added Column default and onupdate on update and add
(only for scalar values and callables)Added small proxy prop on OMDatabaes, to raw asyncpg connection0.1.8Yaml data importer0.1.7Support adding basic inherited models0.1.6query should be an async iterator0.1.5Load inherited models.0.1.4query(Object).get should return None if not found0.1.3Fixes and improvements. Lay out basic API0.1.0 (2019-04-07)First release on PyPI.
Package: asynconsumer
asynconsumerasynconsumer is a simple library for processing each items within iterable using asyncio.How to install$pip3installasynconsumerQuick startDefine a function or a coroutine function which takes one argument.Now, callasync_run(iterable, function)and you can get list which each items was applied with the function.concurrencyis an optional parameter can changes number of concurrently executed coroutines(default: 1).Examplescoroin the following code is a coroutine function that convert a word passed as an argument to an upper case.So,async_run(['ham', 'egg', 'spam'], coro, concurrency=2)will return['HAM', 'EGG', 'SPAM'].>>>fromasynconsumer.coreimportasync_run>>>importasyncio>>>asyncdefcoro(target):...print('start:{}'.format(target))...awaitasyncio.sleep(1)...print('end:{}'.format(target))...returntarget.upper()...>>>results=async_run(['ham','egg','spam'],coro,concurrency=2)start:hamstart:eggend:hamend:eggstart:spamend:spam>>>results['HAM','EGG','SPAM']>>>You can also pass the normal functions.>>>fromasynconsumer.coreimportasync_run>>>importtime>>>deffunc(target):...print('start:{}'.format(target))...time.sleep(1)...print('end:{}'.format(target))...returntarget.upper()...>>>results=async_run(['ham','egg','spam'],func,concurrency=2)start:hamstart:eggend:hamend:eggstart:spamend:spam>>>results['HAM','EGG','SPAM']>>>More samples.Sample codes are put inasynconsumer/samples.Concurrent get HTTP resources$pip3installaiohttp$python3-q>>>fromasynconsumerimportfetch_http_resources>>>urls=['https://avatars3.githubusercontent.com/u/13819005?s=460&v=4']>>>fetch_http_resources(urls,'.')['./8ee20d7c992fee4ac009f4d33c13e276']>>>>>>fetch_http_resources(urls=urls,directory='.',naming=lambdaurl:'image_{}.jpg'.format(urls.index(url)))['./image_0.jpg']Concurrent get GCS objects$pip3installgoogle-cloud-storage$python3-q>>>fromasynconsumerimportfetch_gcs_objects>>>uris=['gs://...']>>>fetch_gcs_objects(uris,'.')['./md5string']>>>>>>fetch_http_resources(uris,'.',naming=lambdauri:'image_{}.jpg'.format(uris.index(uri)))['./image_0.jpg']
Package: asyncopoisk
AsyncopoiskЭто асинхронная обертка дляKinopoisk API Unofficial. Создавалась для личного пользования, так как удобной и асинхронной обертки найти не смог. Это был мой первый опыт в написании АПИ обертки, так что PR и Issue приветствуются!ОсобенностиВ обертки реализованы все методы, что были описаны вдокументациина момент2023.21.12структура запросов сделана так, чтобы минимально отличаться отдокументациисамой АПИНачало работыПеред использованием asyncopoisk вам нужно получить токен. Получить его можно на сайтеKinopoisk API UnofficialУстановите AsyncopoiskpipinstallasyncopoiskДалее создайте экземпляр оберткиfromasyncopoiskimportKinopoiskAPIkp=KinopoiskAPI(token="TOKEN")Теперь с помощьюkpвы можете вызывать методы АПИ.ВАЖНОтак как обертка использует асинхронную httpx сессию, вызов всех методов должен происходить асинхронноПримерыПолучить данные о фильме по kinopoisk idimportasynciofromasyncopoiskimportKinopoiskAPIasyncdefmain(kp_token:str,kp_id:int):kp=KinopoiskAPI(token=kp_token)# Получаем фильм по idfilm=awaitkp.films(kp_id)if__name__=="__main__":asyncio.run(main(kp_token="TOKEN",kp_id=841700))Получить данные о фильме по imdb idimportasynciofromasyncopoiskimportKinopoiskAPIasyncdefmain(kp_token:str,imdb_id:str):kp=KinopoiskAPI(token=kp_token)# Получаем фильм по imdb idfilm=awaitkp.films(imdb_id=imdb_id)if__name__=="__main__":asyncio.run(main(kp_token="TOKEN",imdb_id="tt3659388"))Получить список русских сериалов с рейтингом не ниже 6.5 от 2023 годаНомера стран и жанров можно получить используя методfilms.filters()fromtypingimportListimportasynciofromasyncopoiskimportKinopoiskAPIfromasyncopoisk.models.enumsimportSearchOrder,SearchFilmTypeasyncdefmain(kp_token:str,countries:List[int],order:SearchOrder,type:SearchFilmType,rating_from:float,year_from:int,):kp=KinopoiskAPI(token=kp_token)# Поиск по фильтрамfilm=awaitkp.films(countries=countries,order=order,type=type,rating_from=rating_from,year_from=year_from,)if__name__=="__main__":asyncio.run(main(kp_token="TOKEN",countries=[34],order=SearchOrder.RATING,type=SearchFilmType.TV_SERIES,rating_from=6.5,year_from=2023,))Поиск по ключевому словуimportasynciofromasyncopoiskimportKinopoiskAPIfromasyncopoisk.models.enumsimportSearchOrder,SearchFilmTypeasyncdefmain(kp_token:str,keyword:str):kp=KinopoiskAPI(token=kp_token)# Поиск по ключевому словуresult=awaitkp.films.search_by_keyword(keyword=keyword)if__name__=="__main__":asyncio.run(main(kp_token="2d3c7c68-b288-4fbd-84d8-ccb68e495923",keyword="Марсианин",))Зависимостиpydantic 2.3.0httpx 0.25.0
Package: asyncore-wsgi
This is a single-threaded asynchronous WSGI server with WebSockets support
based onasyncoremodule.
It should be compatible with Python 2.7 and 3.Example:fromfromwsgiref.simple_serverimportdemo_appfromasyncore_wsgiimportAsyncWebSocketHandler,make_serverclassSimpleEchoHandler(AsyncWebSocketHandler):defhandleMessage(self):print('Received WebSocket message:{}'.format(self.data))self.sendMessage(self.data)defhandleConnected(self):print('WebSocket connected')defhandleClose(self):print('WebSocket closed')httpd=make_server('',8000,demo_app,ws_handler_class=SimpleEchoHandler)httpd.serve_forever()The server in the preceding example serves a demo WSGI app from
the Standard Library and the echo WebSocket handler on'/ws'path.WebSocket part was borrowed fromthis project.LicenseMIT, see LICENSE.txt
Package: async-orm
async-ormAsync orm for async web framework, you should use Django to manage your database(ddl etc).pip install -U async-ormUsagefrom django.db import models
from async_orm import BaseModel, transation, Q


class FooBar(BaseModel):
    """ foo bar """

    game = models.CharField(verbose_name='game', max_length=30, blank=False, null=False, db_index=True)
    title = models.CharField(verbose_name='title', max_length=100, blank=False, null=False)
    weight = models.IntegerField(verbose_name='weight', blank=False, null=False, default=0)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        app_label = 'test'
        verbose_name = "foo_bar"
        verbose_name_plural = "foo_bar"
        ordering = ['key', '-title']


async def test_foo_bar():
    game = 'game1'
    title = 'title2'
    # select
    await FooBar.select(where=Q(game=game, title=title) | Q(game='game2'), limit=2, offset=5)
    await FooBar.select(fields=['id', 'title'], order_by=['-title'])
    await FooBar.select(where=Q(weight__gt=0), limit=1)
    await FooBar.select(count=['game'], distinct=True, where=Q(id__gte=2))

    ret = await FooBar.select(where=Q(game='game2'), limit=1)
    if not ret:
        # insert
        ret = FooBar(game='game2', title='title22', weight=0)
        num = await ret.save()
        print(ret.id)
        print(num)
        # result = FooBar.create(game='game2', title='title22', weight=0)
    else:
        # update
        ret.title = 'new title' + str(datetime.datetime.now())
        num = await ret.save()
        print(ret.id)
        print(num)

        # delete
        # num = await ret.delete()
        # print(num)

    # transaction
    if ret is not None:
        async with transaction() as ts:
            await FooBar.create(game='game2', title='ttitle1', weight=0, ts=ts)
            await FooBar.create(game='game2', title='ttitle2', weight=0, ts=ts)
            await FooBar.create(game='game2', title='ttitle3', weight=0, ts=ts)
            await ts.conn.rollback()
            await FooBar.create(game='game2', title='ttitle4', weight=0, ts=ts)
            await ts.conn.commit()
Package: asyncoro
asyncorois a Python framework for
asynchronous, concurrent, distributed programming with coroutines, asynchronous
completions and message passing.Unlike with other asynchronous frameworks, programs developed with asyncoro havesame logic and structureas programs with threads, except for a few
syntactic changes - mostly usingyieldwith asynchronous completions that give
control to asyncoro’s scheduler, which interleaves executions of coroutines,
similar to the way an operating system executes multiple processes. In addition,
asyncoro has many additional features, including message passing for
communication, distributed computing/programming etc.Unlike threads, creating processes (coroutines) with asyncoro is very
efficient. Moreover, with asyncoro context switch occurs only when coroutines
useyield(typically with an asychronous call), so there is no need for
locking and there is no overhead of unnecessary context switches.asyncoro works with Python versions 2.7+ and 3.1+. It has been tested with
Linux, Mac OS X and Windows; it may work on other platforms, too.FeaturesNo callbacks or event loops! No need to lock critical sections either,Efficient polling mechanisms epoll, kqueue, /dev/poll, Windows
I/O Completion Ports (IOCP) for high performance and
scalability,Asynchronous (non-blocking) sockets and pipes, for concurrent
processing of I/O,SSL for security,Asynchronous locking primitives similar to Python threading module,Asynchronous timers and timeouts,Message passingfor (local and remote) coroutines to exchange messages one-to-one
withMessage Queue Patternor through
broadcasting channels withPublish-Subscribe Pattern,Location transparencywith naming
and locating (local and remote) resources,Distributing computation components (code and data) for execution of
distributed communicating processes, for wide range of use cases, coveringSIMD, MISD, MIMDsystem
architectures at the process level,web interfaceto
monitor cluster/application status/performance;in-memory processing, data streaming,
real-time (live) analytics and cloud computing are supported as well,Monitoring and restarting of (local or remote) coroutines, for fault detection
and fault-tolerance,Hot-swapping of coroutine functions, for dynamic system reconfiguration,Thread pools with asynchronous task completions, for executing (external)
synchronous tasks, such as reading standard input.Dependenciesasyncoro is implemented with standard modules in Python.Ifpsutilis available on nodes, node
availability status (CPU, memory and disk) is sent in status messages, and shown
in web browser so node/application performance can be monitored.Under Windows efficient polling notifier I/O Completion Ports (IOCP) is
supported only ifpywin32is available;
otherwise, inefficientselectnotifier is used.InstallationTo install asyncoro, run:python -m pip install asyncoroAuthorsGiridhar PemmasaniLinksProject page.Tutorial/Examples.GitHub (Code Repository).
Package: asyncoss
Based on aiohttp and oss2, Require python3.6+InstallingpipinstallasyncossGetting startedimportasyncossimportasyncioendpoint='http://oss-cn-beijing.aliyuncs.com'auth=asyncoss.Auth('<Your AccessKeyID>','<Your AccessKeySecret>')asyncdefmain():# The object key in the bucket is story.txtasyncwithasyncoss.Bucket(auth,endpoint,'<your bucket name>')asbucket:key='story.txt'# Uploadawaitbucket.put_object(key,'Ali Baba is a happy youth.')# Downloadresult=awaitbucket.get_object(key)awaitresult.resp.read()# Deleteawaitbucket.delete_object(key)loop=asyncio.get_event_loop()loop.run_until_complete(main())
Package: asyncosu
AsyncOsuAsynchronous osu! api wrapper for python using aiohttp.OsuApiV2This package supportsosu api v2.Basic usage with context manager:importasynciofromasyncosuimportOsuApiV2asyncdefmain():asyncwithOsuApiV2(client_id='client_id',client_secret='client_secret')asosu_api:returnawaitosu_api.get_user_from_username(f'heyronii')if__name__=="__main__":print(asyncio.run(main()))without context_manager:asyncdefmain():osu_api=OsuApiV2(client_id='client_id',client_secret='client_secret')user_info=awaitosu_api.get_user_from_username(f'heyronii')awaitosu_api.close()# Close the connection before creating another instancereturnuser_info
Package: asyncowfs
This library allows you to access 1wire buses with Python, using any
async library (trio, asyncio, curio).This code doesnottry to talk to any 1wire interface by itself; it
uses TCP port 4304 (by default) to access one or moreowservers.Bus enumeration (when starting up, plus periodically in the background
if desired) is automatic and can be turned off.This code supports background polling, alerts, and simultaneous
conversions. Bus couplers (DS2509) are handled transparently. Accessors to
device attributes are created from device descriptors, read fromowserverand augmented by device-specific classes when necessary.The name of this library is (a) historic, (b) its main author strongly
prefers Trio.