Skip to main content

HTTP database access.

Project description

Server Usage

import asyncio
import peewee_async
import peewee_asyncext
import peewee
import aiodata.server as aiodata
import aiohttp.web
import functools

# get event loop
loop = asyncio.get_event_loop()

# create an asyncio-compatible peewee database
database = peewee_asyncext.PostgresqlExtDatabase('test')

# used for async query executions
objects = peewee_async.Manager(database)

# build a model
class Users(peewee.Model):

  name = peewee.TextField(null = True)

  tag = peewee.IntegerField(null = True)

  hobby = peewee.TextField(null = True)

  class Meta:

    database = database

    primary_key = peewee.CompositeKey('name', 'tag')

# ensure it exists
Users.create_table()
# ...do other stuff

# will create a function checking the 'Authorization'
# header of each request for this token and validating;
# raises an aiohttp.web.HTTPUnauthorized error upon failure
authorize = aiodata.utils.authorizer('super secret')

# heartbeat
interval = 30

# create the client;
# for no auth, simply pass `lambda request: None`
client = aiodata.Client(authorize, interval)

# utils.fail is a convenience function for error raising with json data;
# this is the error handlers will raise for bad requests, passing an
# arbitrary amount of positional arguments, starting with a code (str)
# representing the error, ex: error('database error', output)
fail = functools.partial(aiodata.utils.fail, aiohttp.web.HTTPBadRequest)

# make the application
app = aiohttp.web.Application()

# will create handlers and then dispatchers for the client;
# also saves information related to the smooth execution of
# websocket connections utilized by the peers - important!
# yields route assets in the form of (method, path, handler)
routes = aiodata.utils.setup(client, objects, Users, authorize, fail)

# iterate through
for route in routes:

  # and add them to our router
  app.router.add_route(*route)

# also add some route for the websocket connection
app.router.add_route('GET', '/state', client.connect)

# disable sync
database.set_allow_sync(False)

# run the app localy
aiohttp.web.run_app(app)

Requests should be in the form of METHOD */model with json [keys, data].

import requests

url = 'http://localhost:8080/users'

keys = ['cat', 40]

data = {'hobby': 'meowing'}

body = [keys, data]

headers = {'Authorization': 'super secret'}

response = requests.post(url, json = body, headers = headers)

# will be an array of dicts as rows with all their columns;
# every successful request returns all the rows affected
entries = response.json()

print(entries)

Client Usage

import asyncio
import aiohttp
import aiodata.client as aiodata

# get event loop
loop = asyncio.get_event_loop()

# create the session
session = aiohttp.ClientSession(loop = loop)

# beep boop
host = 'http://localhost:8080'

# create a function injecting the headers
# with an 'Authorization' key against this token
authorize = aiodata.utils.authorizer('super secret')

# create the client;
# for no auth, simply pass `lambda kwargs: None`
client = aiodata.Client(session, host, authorize)

# listen for rows being updated
@client.track('update', 'users')
async def listener(entries):

  for before, after in entries:

    for key, value in before.items():

      check = after[key]

      if value == check:

        continue

      print('changed', key, 'from', value, 'to', check)

# demonstration
async def execute():

  # will connect to websocket,
  # receive info, build, fill cache,
  # listen for database interactions
  await client.start('/state')

  # cache can be poked like so;
  # entries are simple objects,
  # tables are overwritten dicts
  entry = client.cache.users.get('cat', 40)

  # see before
  print(entry.hobby)

  # change the tag (primary) and hobby
  # make a request, patching all rows with 'cat' as name;
  # the positional nature of the keys implies entries
  # can't be bulk edited by leading primary keys alone
  entries = await client.update('cat', tag = 80, hobby = 'barking')

  print(entries)

  await client.close()

  await session.close()

coroutine = execute()

loop.run_until_complete(coroutine)

Installing

python3 -m pip install aiodata

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

aiodata-1.4.0.tar.gz (11.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

aiodata-1.4.0-py3-none-any.whl (14.0 kB view details)

Uploaded Python 3

File details

Details for the file aiodata-1.4.0.tar.gz.

File metadata

  • Download URL: aiodata-1.4.0.tar.gz
  • Upload date:
  • Size: 11.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.12.1 pkginfo/1.5.0.1 requests/2.20.0 setuptools/40.8.0 requests-toolbelt/0.8.0 tqdm/4.29.1 CPython/3.7.3

File hashes

Hashes for aiodata-1.4.0.tar.gz
Algorithm Hash digest
SHA256 d206e6537fbd3cc03e94f024c3deda75263255f97d7f2cd0fc0751939ff33365
MD5 3006ae4a04a3e942bea3eb3ffee74bfd
BLAKE2b-256 7b376435951aea08f4b5ffcf8781b3776dd789af9e18ceb5b09338ea1985b415

See more details on using hashes here.

File details

Details for the file aiodata-1.4.0-py3-none-any.whl.

File metadata

  • Download URL: aiodata-1.4.0-py3-none-any.whl
  • Upload date:
  • Size: 14.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.12.1 pkginfo/1.5.0.1 requests/2.20.0 setuptools/40.8.0 requests-toolbelt/0.8.0 tqdm/4.29.1 CPython/3.7.3

File hashes

Hashes for aiodata-1.4.0-py3-none-any.whl
Algorithm Hash digest
SHA256 038def8a3eaaf9f3eeab06f70085e0b9824db8c160b933b7e5de50dfa1c5a5ea
MD5 2ae6f433eb0da7d9c497f791c0c765d4
BLAKE2b-256 092fb898f55f87cf28ef05e9af2e0b00af7c21f1bd903b8d58006347d8249330

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page