- Author:
- msmenzyk
- Posted:
- January 20, 2011
- Language:
- Python
- Version:
- Not specified
- Score:
- 0 (after 0 ratings)
How connect to API Infakt.pl from Python. Snippet is django command managment. Use: e.g: python manage.py sync_clients_from_infakt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | # -*- coding: utf-8 -*-
import urllib2
from xml.dom import minidom
from django.core.management.base import NoArgsCommand
class Command(NoArgsCommand):
"""
<clients type="array">
<client>
<adres-www>www.example.com</adres-www>
<email>[email protected]</email>
<id type="integer">666</id>
<info>Services</info>
<kod-pocztowy>33-350</kod-pocztowy>
<miejscowosc>Kraków</miejscowosc>
<nazwa-firmy>Some company</nazwa-firmy>
<nip>123 456 78 90</nip>
<numer-telefonu>666 667 668</numer-telefonu>
<ulica>ul. test</ulica>
</client>
</clients>
"""
help = 'Connect to Infakt API'
def handle_noargs(self, **options):
api_key = "API_KEY_FROM_INFAKT"
uri = 'http://www.infakt.pl'
username = 'YOUR_USERNAME'
password = 'YOUR_PASSWORD' + api_key
try:
auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(realm='Application',
uri=uri,
user=username,
passwd=password)
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
# get clients from infakt
response = urllib2.urlopen(uri+"/api/clients.xml")
xmlString = response.read()
xml = minidom.parseString(xmlString)
cnt = 0
for client in xml.getElementsByTagName('client'):
cnt += 1
def _get(n):
try:
return client.getElementsByTagName(n)[0].firstChild.data
except AttributeError, e:
return None
infakt_id = _get('id')
legal_name = _get('nazwa-firmy')
nip = _get('nip')
notes = _get('info') or " " + "(Infakt id: %s)" % infakt_id
website = _get('adres-www')
email = _get('email')
phone = _get('numer-telefonu')
zip_code = _get('kod-pocztowy')
city = _get('miejscowosc')
street = _get('ulica')
#
# Import Company or other model from your models and sync them
#
try:
company = Company.objects.get(infakt_id=infakt_id)
except Company.DoesNotExist:
company = Company()
company.legal_name=legal_name
company.nip=nip
company.notes=notes
company.infakt_id=infakt_id
company.save()
print company
except Exception, e:
print 'Nie mozna uzyskac listy klientow z API Infakt! (%s)' % e
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.