Giter Club home page Giter Club logo

python-phant's Introduction

python-phant

A Python client library for Phant. See data.sparkfun.com for more information.

Installation

Either

  • copy the phant module into you source tree or
  • run python setup.py install or
  • install with pip install phant.

Usage

A basic example of connecting and logging data. Note that collecting some of the information around API rate limits only works after a log() command

import sys
from phant import Phant
p = Phant(publicKey='xyzpublickey', fields=['temp', 'humid'], privateKey='abcprivatekey')

t = 33.4
h = 10.2
p.log(t, h)
print(p.remaining_bytes, p.cap)

data = p.get()
print(data['temp'])

Additionally, the json file generated during stream creation can be provided to the constructor:

import phant
p=phant.Phant(jsonPath='/path/to/my/keys_xyzpublickey.json')

Another example, this time limiting to 10 results, and only if the temperature was '9'.

p.get(
    eq=("temp","9"),
    limit=10
)

Encoders

By default, data is serialiced in order to be stored using json format.

Other encoders can be defined in order to provide support for more complex data structures. Take a look at phant.encoders.complex to see a simple example implementing serialization of complex numbers.

To use this feature:

import phant
import phant.encoders.complex

p=phant.Phant(jsonPath='python-phant/keys.json', encoder=phant.encoders.complex)

p.log(1,2,3,4+6j)

p.get(limit=1)

[{u't': 1,
  u'timestamp': datetime.datetime(2016, 1, 7, 15, 47, 56, 420000),
  u'x': 2,
  u'y': 3,
  u'z': (4+6j)}]

As you can see, complex numbers are correctly logged and got.

If now we try to get the same values using the default encoder (plain_json):

p=phant.Phant(jsonPath='python-phant/keys.json')

p.get(limit=1)
 
[{u't': 1,
  u'timestamp': datetime.datetime(2016, 1, 7, 15, 47, 56, 420000),
  u'x': 2,
  u'y': 3,
  u'z': {u'__complex__': True, u'imag': 6.0, u'real': 4.0}}]

We get a dictionary with the encoded complex number.

Additionally, trying with no encoders at all you'll notice everything is stored just as plain strings:

import phant.encoders.null

p=phant.Phant(jsonPath='python-phant/keys.json', encoder=phant.encoders.null)

p.get(limit=1)
 
[{u't': u'1',
  u'timestamp': datetime.datetime(2016, 1, 7, 15, 47, 56, 420000),
  u'x': u'2',
  u'y': u'3',
  u'z': u'{"real": 4.0, "imag": 6.0, "__complex__": true}'}]

Note you won't be able to log a complex number with neither ´plain_json´ or ´null´ encoders, getting a TypeError exception. Same thing happens if you try to log a list or a dictionary with null encoder.

python-phant's People

Contributors

jrleeman avatar lewispurigenbio avatar lowks avatar matze avatar mcowger avatar spuder avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

python-phant's Issues

how to conceal private key in the python code?

i always need to write my private key explicitly in the python code:
p = Phant(publicKey='xyzpublickey', fields=['temp', 'humid'], privateKey='abcprivatekey')

is there any way i can conceal my private key as i did in wpa_supplicant?
password=hash:7c2d7f0711f29d05c5dfd95e9df04e0c

thanks

AttributeError: 'Phant' object has no attribute '_get_url'

Hi,

I've just downloaded the current version, and execute it with Python 2.7 on Synology.

Here is the command line :
python testPhant.py

The file contain the example from Github.

The full error :

Traceback (most recent call last):
File "testPhant.py", line 3, in
p = Phant(publicKey='xxxxx', fields=['test1', 'test2'], privateKey='xxxxxxx')
File "/usr/local/lib/python2.7/site-packages/phant-0.6dev-py2.7.egg/phant/init.py", line 45, in init
'inputUrl': self._get_url('input', extension=''),
AttributeError: 'Phant' object has no attribute '_get_url'

Regards,
Joseph

Filtering the get() not working

I can't seem to get the get() to work:

data = stream.get(gte=('temp','10'))

Traceback (most recent call last):
  File ".\test1.py", line 29, in <module>
    data = stream.get(gte=('temp','10'))
  File "C:\Python27\lib\site-packages\phant-0.6.dev0-py2.7.egg\phant\__init__.py", line 257, in get
    if gte and self._check_limit_tuple(gte):
  File "C:\Python27\lib\site-packages\phant-0.6.dev0-py2.7.egg\phant\__init__.py", line 177, in _check_limit_tuple
    limit_tuple[0], self.fields))
ValueError: Field 'temp' not in the known list of fields: [u'foggy', u'temp']

NameError: name 'Phant' is not defined

Having a hard time getting this module to work with python 2.7.3. Following the instructions in the README.

cd /tmp
git clone https://github.com/matze/python-phant.git
cp /tmp/python-phant/phant.py ~/
python ~/foo.py
raceback (most recent call last):
  File "foo.py", line 42, in <module>
    p = Phant('xxxxx', data['humidity'], data['tempc'], data['tempf'], private_key='xxxxx')
NameError: name 'Phant' is not defined

Also tried installing the module with

sudo pip install phant

and

sudo python /tmp/python-phant/setup.py install

The script looks like

import sys
import Adafruit_DHT
import phant
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
data = {}
if humidity is not None and temperature is not None:
        data['humidity'] = humidity
        data['tempc'] = temperature
        data['tempf'] = temperature * 9/5.0 + 32
        print data
        p = Phant('xxxxx', data['humidity'], data['tempc'], data['tempf'], private_key='xxxxx')
        p.log(33.4, 10.2)
        print(p.remaining_bytes, p.cap)
else:
        print 'Failed to get reading. Try again!'
        sys.exit(1)

Also looking at the tests.py and I see the following syntax.

            p = phant.Phant(PUBLIC, 'field', private_key=PRIVATE)

That returns the same error.

Is there an example repo anywhere that shows this library actually being used?

Issues with python on windows

Hello,

Thank you for writing this library. I had to modify _get_url in order to get this library to work on windows. Python 2.7.
This line:
os.path.join(self.base_url, command, self.public_key) + ext
would give me http://data.sparkfun.com/input\\publickey.json
as an ugly hack, I modified it to:
b = str(self.base_url) + str(command) + "/" + str(self.public_key) + ext
return b

I'm sure there is a better way, but this works for me on both windows and linux python 2.7.x

Error __init__() takes at least 2 arguments (1 given)

Trying to play with the python library installed through pip gives me an error.

pi@openthing ~ $ python
Python 2.7.3 (default, Mar 18 2014, 05:13:23)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.

import sys
from phant import Phant
import phant
p=phant.Phant(jsonPath='/home/pi/phant_key.json')
Traceback (most recent call last):
File "", line 1, in
TypeError: init() takes at least 2 arguments (1 given)

This error occurs on both Raspberry Pi and Ubuntu on x86

Tests failing for python 3

Tests seem to be failing under python 3. I tested the code manually under python 3 and no errors are thrown which leads me to believe that it is just a problem with the tests.

I have included the traceback with the results.

ERROR: test_stats (tests.RequestTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/travis/build/gunthercox/python-phant/tests.py", line 45, in test_stats
    remaining, used = p.remaining_bytes, p.used_bytes
  File "/home/travis/build/gunthercox/python-phant/phant.py", line 96, in remaining_bytes
    return self._get_stat('remaining')
  File "/home/travis/build/gunthercox/python-phant/phant.py", line 119, in _get_stat
    self._stats = response.json()
  File "/home/travis/virtualenv/python3.4.1/lib/python3.4/site-packages/requests/models.py", line 753, in json
    encoding = guess_json_utf(self.content)
  File "/home/travis/virtualenv/python3.4.1/lib/python3.4/site-packages/requests/utils.py", line 612, in guess_json_utf
    nullcount = sample.count(_null)
TypeError: Can't convert 'bytes' object to str implicitly

get() - offset and sample parameters are handled wrong

if offset:
if not isinstance(offset, int):
raise ValueError("Offset must be an int")
params['offset'] = limit <<--- Should be offset

    if sample:
        if not isinstance(sample, int):
            raise ValueError("Sample must be an int")
        params['sample'] = limit <<--- Should be sample

TypeError: __init__() takes at least 2 arguments (1 given)

If I try to run the basic example:

import sys
from phant import Phant
p = Phant(publicKey='xyzpublickey', fields=['temp', 'humid'], privateKey='abcprivatekey')

t = 33.4
h = 10.2
p.log(t, h)
print(p.remaining_bytes, p.cap)

data = p.get()
print(data['temp'])

This returns:

Traceback (most recent call last):
  File ".\test1.py", line 3, in <module>
    p = Phant(publicKey='xyzpublickey', fields=['temp', 'humid'], privateKey='abcprivatekey')
TypeError: __init__() takes at least 2 arguments (1 given)

I'm using Python 2.7.12 and phant-0.4

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.