Giter VIP home page Giter VIP logo

dnsimple-python's Introduction

DNSimple Python Client

A Python client for the DNSimple API v2.

CI

Documentation

Requirements

  • Python 3.12 - Note later versions of Python may be supported, but we make no guarantees as they are not tracked in our CI.

Installation

Where <version> denotes the version of the client you want to install.

To install the latest version:

pip install dnsimple

To install a specific version:

pip install dnsimple==2.0.1

Usage

This library is a Python client you can use to interact with the DNSimple API v2. Here are some examples.

from dnsimple import Client

client = Client(access_token='a1b2c3')

# Fetch your details
response = client.identity.whoami()             # execute the call
data = response.data                            # extract the relevant data from the response or
account = client.identity.whoami().data.account # execute the call and get the data in one line

Sandbox Environment

We highly recommend testing against our sandbox environment before using our production environment. This will allow you to avoid real purchases, live charges on your credit card, and reduce the chance of your running up against rate limits.

The client supports both the production and sandbox environment. To switch to sandbox pass the sandbox API host using the base_url option when you construct the client:

from dnsimple import Client

client = Client(base_url='https://api.sandbox.dnsimple.com', access_token="a1b2c3")

You can also set the sandbox environment like so:

from dnsimple import Client

client = Client(sandbox=True, access_token='a1b2c3')

You will need to ensure that you are using an access token created in the sandbox environment. Production tokens will not work in the sandbox environment.

Define an account ID

from dnsimple import Client

client = Client(access_token='a1b2c3')
account_id = 1010

# You can also fetch it from the whoami response
# as long as you authenticate with an Account access token
whoami = client.identity.whoami().data
account_id = whoami.account.id

List your domains

from dnsimple import Client

client = Client(access_token='a1b2c3')

account_id = client.identity.whoami().data.account.id
domains = client.domains.list_domains(account_id).data                           # Domains from the 1010 account (first page)
client.domains.list_domains(account_id, sort='expires_on:asc').data              # Domains from the 1010 account in ascending order by domain expiration date
client.domains.list_domains(account_id, filter={'name_like': 'example'}).data    # Domains from the 1010 account filtered by the domain name name

Create a domain

from dnsimple import Client

client = Client(access_token='a1b2c3')

account_id = client.identity.whoami().data.account.id
response = client.domains.create_domain(account_id, 'example.com')
domain = response.data # The newly created domain

Get a domain

from dnsimple import Client

client = Client(access_token='a1b2c3')

account_id = client.identity.whoami().data.account.id
domain_id = client.domains.list_domains(account_id).data[0].id
domain = client.domains.get_domain(account_id, domain_id).data # The domain you are looking for

Setting a custom User-Agent header

You customize the User-Agent header for the calls made to the DNSimple API:

from dnsimple import Client

client = Client(user_agent="my-app")

The value you provide will be appended to the default User-Agent the client uses. For example, if you use my-app, the final header value will be my-app dnsimple-python/0.1.0 (note that it will vary depending on the client version).

Contributing

Contibutions are welcomed. Please open an issue to discuss the changes before opening a PR. For more details on how to do development please refer to CONTRIBUTING.md

License

Copyright (c) 2022 DNSimple Corporation. This is Free Software distributed under the MIT license.

dnsimple-python's People

Contributors

ags4no avatar colbyprior avatar dcrosta avatar dependabot-preview[bot] avatar dependabot[bot] avatar deviatefish avatar digitronik avatar drcapulet avatar drpotato avatar dxtimer avatar ecomba avatar ggalmazor avatar jacegu avatar jmurty avatar joshbrooks avatar kevchentw avatar kntsoriano avatar lcd1232 avatar mdippery avatar mherrmann avatar mikemaccana avatar mjacksonw avatar nestorsalceda avatar olemchls avatar onlyhavecans avatar pkaeding avatar pwnall avatar pztrick avatar reagent avatar weppos 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dnsimple-python's Issues

client.zones.delete_record gives JSONDecodeError

I'm on Python 3.7 and am using version version 2.0.0 of the library. I am also on requests version 2.24.0.

When I try to delete a record with the following code:

from dnsimple import Client
client = Client(access_token='...')
account_id = client.identity.whoami().data.account.id
client.zones.delete_record(account_id, 'mydomain.com', my_record_id)

Then I get the following stack trace:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/michael/dev/tutorial/main/dnsimple.py", line 22, in delete_a_record
    client.zones.delete_record(account_id, main, record.id)
  File "/home/michael/dev/tutorial/venv/lib/python3.7/site-packages/dnsimple/service/zones.py", line 213, in delete_record
    return Response(response)
  File "/home/michael/dev/tutorial/venv/lib/python3.7/site-packages/dnsimple/response.py", line 54, in __init__
    self.__class__.pagination = None if http_response.json().get('pagination') is None else Pagination(
  File "/home/michael/dev/tutorial/venv/lib/python3.7/site-packages/requests/models.py", line 898, in json
    return complexjson.loads(self.text, **kwargs)
  File "/usr/lib/python3.7/json/__init__.py", line 348, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.7/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.7/json/decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Despite the error, the record is successfully deleted from my account.

And I think I know why. I debugged into your code. Deleting the zone returns a response with an empty body. Precisely, response.text is '' and response.content is b'' in zones.py:213. Digging further, I think the mistake is in response.py:53, where you have:

if http_response.status_code != '204':
    ...

I think this should be

if http_response.status_code != 204:
    ...

ImportError: cannot import name 'Client' from partially initialized module 'dnsimple'

from dnsimple import Client
from dnsimple.struct import Contact, DomainRegistrationRequest

# Obtain your API token and Account ID
# https://support.dnsimple.com/articles/api-access-token/
client = Client(access_token="TOKEN")

account_id = 9999999

# Check for domain availability
response = client.registrar.check_domain(
      account_id,
      'google.com'
  )

print(response.data.available)

RESULT:

nv) C:\Users\SEO\Desktop\Python>C:/Users/SEO/anaconda3/envs/mainEnv/python.exe "c:/Users/SEO/Desktop/Python/Projects/Domain Backorder/Backorder/dnsimple.py"
Traceback (most recent call last):
File "c:\Users\SEO\Desktop\Python\Projects\Domain Backorder\Backorder\dnsimple.py", line 1, in
from dnsimple import Client
File "c:\Users\SEO\Desktop\Python\Projects\Domain Backorder\Backorder\dnsimple.py", line 1, in
from dnsimple import Client
ImportError: cannot import name 'Client' from partially initialized module 'dnsimple' (most likely due to a circular import) (c:\Users\SEO\Desktop\Python\Projects\Domain Backorder\Backorder\dnsimple.py)

At the first time when i tried it worked but after that try, i always get this error?
How can i fix this?
Thanks

TypeError: option values must be strings

Using the .dnsimple file authentication option results in a TypeError: option values must be strings error.

I believe this occurs do to a change in ConfigParser for Python3.7. I fixed it by setting allow_no_value=True in the ConfigParser call on line 104 of dnsimple.py.

Dosn't work?

I can't seem to get it to Authorize?

Is this up-to-date with the current API -- I don't see python listed on the site?

Thanks!

Casey

1.0.1 pip install failing

I'm unable to pip install 1.0.1, it's failing on NameError: name 'AuthBase' is not defined

The same error is happening in travis, but the build doesn't fail because of this.

https://travis-ci.org/onlyhavecans/dnsimple-python/jobs/344629037#L474

Traceback (most recent call last):
  File "setup.py", line 6, in <module>
    from dnsimple import dnsimple
  File "/home/travis/build/onlyhavecans/dnsimple-python/dnsimple/__init__.py", line 5, in <module>
    from dnsimple.dnsimple import DNSimple, DNSimpleException, DNSimpleAuthException
  File "/home/travis/build/onlyhavecans/dnsimple-python/dnsimple/dnsimple.py", line 47, in <module>
    class DNSimpleTokenAuth(AuthBase):
NameError: name 'AuthBase' is not defined

As an aside: was the removal of the the 0.3.6 package from pypi intentional?

Add to PyPi

Could you please add dnsimple-python package to PyPi? It would be much easier to deploy project using your awesome package.

Cheers :)

Support API v2

This package appears to only support version 1 of the DNSimple API, which is currently scheduled to be discontinued on October 1, 2017. Support for version 2 of the API is needed instead.

Failed to reach a server: Unprocessable Entity (Is this module still functionable?)

I don't see any activity on here in the last year. I'm trying to use the dnsimple-python module but running into some errors from the API. Before I spend a bunch more time trying to figure out the problem (and assuming that I'm doing something wrong), is this still in working order or am I better off reimplenting the api access myself?

Here's the trace:

Traceback (most recent call last):
  File "updater.py", line 63, in <module>
    main(domains, ip)
  File "updater.py", line 61, in main
    update_domain_ip(domain["domain"], name,  ip)
  File "updater.py", line 51, in update_domain_ip
    return create_record(domain, name, ip)
  File "updater.py", line 44, in create_record
    response = dns.add_record(domain, new)
  File "/home/bob/.virtualenvs/dns-updater/lib/python2.7/site-packages/dnsimple/dnsimple.py", line 243, in add_record
    data, method='POST')
  File "/home/bob/.virtualenvs/dns-updater/lib/python2.7/site-packages/dnsimple/dnsimple.py", line 108, in __resthelper
    result = self.__requesthelper(request, http_codes)
  File "/home/bob/.virtualenvs/dns-updater/lib/python2.7/site-packages/dnsimple/dnsimple.py", line 129, in __requesthelper
    % e.reason)
dnsimple.dnsimple.DNSimpleException: Failed to reach a server: Unprocessable Entity

My code is located here:

https://github.com/bobjohnbob/dnsimple-updater/blob/master/updater.py

Thanks,

-John

list_contacts returns a list of the same contact instead of a list of all contacts

Hi All,

When calling list_contacts function from the contacts service returns a list of all of the same contacts.

For example (I changed my contact id to 12345 for the example):

>>> contact_list = client.contacts.list_contacts(account_id)
>>> for contact in contact_list.data:
...     print(contact.id)
...
12345
12345
12345
>>>

The contact struct gets overwritten when it is created.

main...colbyprior:main
Running the code above with this fix I then get three different contact id's as is intended.

TypeError: sequence item 0: expected str instance, int found

On line 145 fail to render the error message.
raise DNSimpleException('Account {} not found. Possible variants: {}'.format(self._account_id, ', '.join(ids)))
File "/usr/local/lib/python3.6/dist-packages/dnsimple/dnsimple.py", line 145, in account_id
', '.join(ids)))
TypeError: sequence item 0: expected str instance, int found
But even if I remove the part to be rendered fail throwing the exception "Account not found|" but my account exists.
This is how I have instantiated the client.
dns_client = DNSimple(api_token=''xxxxxx, account_id='xxxx')
Python 3.6.9

Add rest of API?

Any chance of adding the other portions of the API? Like the ability to add services and other API functions?

dns.check sometimes fail on some domain name

In [16]: dns.check('goolge.com')
Out[16]: 
{u'currency': u'USD',
 u'currency_symbol': u'$',
 u'minimum_number_of_years': 1,
 u'name': u'goolge.com',
 u'price': u'14.00',
 u'status': u'unavailable'}

In [17]: dns.check('iroirsdelame.com')
---------------------------------------------------------------------------
DNSimpleException                         Traceback (most recent call last)
/Users/patate/sandbox/sg/boilerplate/<ipython-input-17-dde2a1a80763> in <module>()
----> 1 dns.check('iroirsdelame.com')

/Users/patate/sandbox/sg/boilerplate/env/lib/python2.7/site-packages/dnsimple/dnsimple.pyc in check(self, domainname)
    164     def check(self, domainname):
    165         """ Check if domain is available for registration """
--> 166         return self.__resthelper('/domains/' + domainname + '/check')
    167 
    168     def register(self, domainname, registrant_id=None):

/Users/patate/sandbox/sg/boilerplate/env/lib/python2.7/site-packages/dnsimple/dnsimple.pyc in __resthelper(self, url, postdata, method)
    100         if method is not None:
    101             request.get_method = lambda: method
--> 102         result = self.__requesthelper(request)
    103         if result:
    104             return json.loads(result)

/Users/patate/sandbox/sg/boilerplate/env/lib/python2.7/site-packages/dnsimple/dnsimple.pyc in __requesthelper(self, request)
    115                 raise DNSimpleException(
    116                     'Failed to reach a server: %s'
--> 117                     % e.reason)
    118             elif hasattr(e, 'code'):
    119                 raise DNSimpleException(

DNSimpleException: Failed to reach a server: Not Found

ZoneRecordInput omits empty name when serialized to json

Hey, when trying to create a record at the apex I get a 400:

Reason: Bad Request
HTTP response body: {"message":"Validation failed","errors":{"name":["can't be null"]}}

Here is the code:

record = ZoneRecordInput(name="", type="CAA", ttl=60, content='0 issuewild "sectigo.com"')
client.zones.create_record(
                account_id,
                "example.com",
                record,
            )

The to_json() function removes empty fields and thus removed the name. However this field is required when using create_record making it impossible to create an apex level record.

API v2 may break ansible deployment due to pagination

Version 2 of the API introduces pagination to any request returning a list - from the docs

Any API endpoint that returns a list of items requires pagination. By default we will return 30 records from any listing endpoint.

This lead to the dnsimple module in Ansible often failing (wherever there are more than 30 items returned - in our case we have 180+ records) with an error message about zones already existing.

There's a work around via a hacked version of dnsimple-python at this repo which 'depaginates' those requests and renames parameters returned by 'records' to what ansible expects for priority and record type fields.

Make DNSimpleException more informative

DNSimpleException currently does not output any information about what went wrong, which makes failures quite hard to debug.

Here's an example interactive session;

In [93]: resp = dnsimple_client.zones.create_record("mi-account-id", "mi.domain.name", test_record_data)
---------------------------------------------------------------------------
DNSimpleException                         Traceback (most recent call last)
~/directory/directory/traveller/enums.py in <module>
----> 1 resp = dnsimple_client.zones.create_record("mi-account-id", "mi.domain.name", test_record_data)

~/.virtualenvs/directory/lib/python3.8/site-packages/dnsimple/service/zones.py in create_record(self, account_id, zone, record)
    152         """
    153         response = self.client.post(f'/{account_id}/zones/{zone}/records', data=record.to_json())
--> 154         return Response(response, ZoneRecord)
    155
    156     def get_record(self, account_id, zone, record_id):

~/.virtualenvs/directory/lib/python3.8/site-packages/dnsimple/response.py in __init__(self, http_response, obj)
     41             if http_response.json().get('errors'):
     42                 errors = http_response.json().get('errors')
---> 43             raise DNSimpleException(message=message, errors=errors)
     44
     45         self.__class__.http_response = http_response

DNSimpleException:

In this particular case, the call failed because the content was malformed (it wasn't a proper domain name). This would have been very useful information to receive back, as the caller.

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.