[PYTHON] A class that hits the DMM API

Click here for DMM API specifications https://affiliate.dmm.com/api/ It just returns XML, so you can parse it or whatever you like ...


#coding:utf-8
import urllib2
import time

"""
Get product information using DMM API
"""

class Dmm:
    def __init__(self, api_id, affiliate_id):
        """constructor"""
        self.baseurl = "http://affiliate-api.dmm.com/"
        self.proxy_host = None
        self.proxy_port = None
        self.api_id = api_id
        self.affiliate_id = affiliate_id
        self.version = "1.0.0"
        self.site = 'DMM.co.jp'
        self.service = 'digital'
        self.operation = 'ItemList'
        
        self.url = None
    
    def setProxy(self, host, port=8080):
        """Set proxy"""
        self.proxy_host = host
        self.proxy_port = port
    
    def setVersion(self, version):
        """Set version"""
        self.version = version
    def setSite(self, site):
        """Set Site"""
        self.site = site
    def setService(self, service):
        """Set Service"""
        self.service = service
    
    def keywordSearch(self, keyword, **options):
        """Search for items"""
        params = options
        params["keyword"] = keyword
        return unicode(self.sendRequest(params),'euc-jp')
        #return self.buildURL(params)
    
    def buildURL(self, params):
        """Construct URL address for REST request"""
        params["api_id"] = self.api_id
        params["affiliate_id"] = self.affiliate_id
        params["version"] = self.version
        params["site"] = self.site
        params["service"] = self.service
        params["operation"] = self.operation
        params["timestamp"] = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
        sorted_params = sorted(params.items())
        
        #Expand hash of params
        request = []
        for p in sorted_params:
            pair = "%s=%s" % (p[0], urllib2.quote(p[1].encode("euc-jp")))
            request.append(pair)
        
        url = self.baseurl + "?" + "&".join(request)
        
        return url
        
    def sendRequest(self, params):
        """Send a request to the DMM and return the retrieved XML"""
        self.url = self.buildURL(params)
        if self.proxy_host:
            proxy_handler = urllib2.ProxyHandler({"http":"http://%s:%s/" % (self.proxy_host, self.proxy_port)})
            opener = urllib2.build_opener(proxy_handler)
        else:
            opener = urllib2.build_opener()
        return opener.open(self.url).read()
    
def _test():
    dmm = Dmm('API key', 'Affiliate')
    print dmm.keywordSearch('sex',hits='100')

if __name__ == '__main__':
    _test()

Recommended Posts

A class that hits the DMM API
Creating a Python script that supports the e-Stat API (ver.2)
A class that summarizes frequently used methods in twitter api (python)
A class that freely changes the PLC value by socket communication
How to send a request to the DMM (FANZA) API with python
A code that corrects the yoon / sokuon (sokuon)
[Python] A program that rounds the score
A story that visualizes the present of Qiita with Qiita API + Elasticsearch + Kibana
Note that the Google Maps Android API GoogleMap.getProjection is not a singleton
Hit a method of a class instance with the Python Bottle Web API
A model that identifies the guitar with fast.ai
I made a LINE BOT that returns a terrorist image using the Flickr API
Created a Python wrapper for the Qiita API
[Python / Tkinter] A class that creates a scrollable Frame
A note on customizing the dict list class
A program that searches for the same image
Python: Prepare a serializer for the class instance:
Use the Kaggle API inside a Docker container
Python: Create a class that supports unpacked assignment
A note about the new style base class
I did a little research on the class
A shell program that displays the Fibonacci sequence
[pyqtgraph] Created a class to display the crosshairs that follow the cursor and their coordinates
A story that reduces the effort of operation / maintenance
Create a fake class that also cheats is instance
[Python] A program that counts the number of valleys
Make a BOT that shortens the URL of Discord
A python implementation of the Bayesian linear regression class
A programming language that protects the people from NHK
# Function that returns the character code of a string
A story that struggled with the common set HTTP_PROXY = ~
PHP and Python samples that hit the ChatWork API
Create a tweet heatmap with the Google Maps API
Generate that shape of the bottom of a PET bottle
A memo that I touched the Datastore with python
How to post a ticket from the Shogun API
A story that analyzed the delivery of Nico Nama.
[Python] A program that compares the positions of kangaroos.
A little bit from Python using the Jenkins API
I wrote a Python script that exports all my posts using the Qiita API v2
A script that makes it easy to create rich menus with the LINE Messaging API
A class that creates DB creation-data insertion with SQLite3 quickly
A program that removes specific characters from the entered text
How to use the __call__ method in a Python class
Launch a simple WEB server that can check the header
Let's make a robot that solves the Rubik's Cube! 2 Algorithm
The story of a Django model field disappearing from a class
I made a class that easily performs unixtime ← → datetime conversion
Create a real-time auto-reply bot using the Twitter Streaming API
A shell script that just emails the SQL execution result
A memo about the behavior of bowtie2 during multiple hits
Let's make a robot that solves the Rubik's Cube! 3 Software
[MQTT / Python] Implemented a class that does MQTT Pub / Sub in Python
A program that just presses and releases the Esc key
Let's make a robot that solves the Rubik's Cube! 1 Overview
Is there a bias in the numbers that appear in the Fibonacci numbers?
Tornado-Let's create a Web API that easily returns JSON with JSON
Create a web API that can deliver images with Django
[Python] A program that finds the most common bird types
Treat the Interface class like that with Python type annotations
A memo that solves the knapsack problem by the greedy algorithm