Python modules restful use method instances

  • 2020-04-02 13:18:15
  • OfStack

RESTful architecture is a popular Internet software architecture. REST, Representational State Transfer.

A white dot is a website as software, and a white dot is a service software to support HTTP four ways:

GET is used to GET resources, POST is used to create and update resources, PUT is used to update resources, and DELETE is used to DELETE resources.

And provide external one or more uris, each URI corresponding to a resource; The client can match the above method with the service through the URI

Segment software interaction. The client side is primarily the browser, and the support for HTTP in software using restful frameworks is also convenient for web applications.

The term REST was coined by Roy Thomas Fielding in his doctoral thesis in 2000. His contributions were many,

You can see that. I work in SDN, which is also a relatively fashionable thing. Floodlight USES a restful framework.

Developers develop features for the software and provide a URI API that users can use to access uris provided by the browser, curl, and others

Get the information you want from the software or set the functionality of the software.

For the developer, it's just a matter of providing the URI and the resource corresponding to the URI, and matching them up, like dicts={'/path? ': the resource}.

For example, override the HTTP GET method: first GET the url requested by the client, parse the url, and then determine its corresponding URI.

Then the url can access the resource. The specific implementation of the resource is a method or a class, depending on the specific implementation.

Here's a very simple example, because this one has a few drawbacks for truly powerful restful, but as a simple demonstration,

That should be enough.


#-*-coding:UTF-8-*-
import socket,sys,urllib
from BaseHTTPServer import *
class Restful(BaseHTTPRequestHandler):  # all rest The parent class 
    def __init__(self,request, client_address, server):
        BaseHTTPRequestHandler.__init__(self,request, client_address, server)
        self.dp=None
        self.router=None

    def basepath(self):
        pass
    def getresetlet(self):
        pass
    def send(self,src):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write(src)
        self.wfile.close()
    def done(self):
        self.dp=self.basepath()
        self.router=self.getrestlet()
class Test(Restful):            # test 1
    def test(self):  # This is a resource 
        return "{"date":"2013-11-19"}"
    def do_GET(self):  # rewrite get Method is given through the client request url Find the corresponding resource 
        self.done()
        for key in self.router.keys():
            tmp=self.dp+key
            if tmp in self.path:
                  self.send(self.router[key]()) # Execution resources 
    def basepath(self): # The simple answer is to match the path in the following function, namely /wm/time
        return "/wm"
    def getrestlet(self):  # Here is the URI Corresponding to the resource, there is only test Resources that can be registered for more than one 
        rr={}
        rr['/time']=self.test 
          return rr
class testjson(Restful):      # test 2
    def testjson(self,vpc,vr):  # Here's a comparison test 1 It's more complicated because the value of the parameter needs to be from url gain 
        src1="{"vpc":1,"vrouter":3,"day":[1,2,3]}"
        src2="{"vpc":1,"vrouter":4,"day":[23,21,3]}"
        src3="{"vpc":5,"vrouter":3,"day":[13,2,23]}"
        tlist=[src1,src2,src3]
        cmpvpc=""vpc":"+vpc
        cmpvr=""vrouter":"+vr
        for k in tlist:
            if cmpvpc in k and cmpvr in k:
                return k
    def firewall(self):
        return "{"filter":["baid.com/","c.cn/"],"acl":{"accept":123,"reject":321}}"
    def do_GET(self):  # rewrite GET , parsing url Here, self.path Similar to: /ins/json?vpc=1&vrouter=3
        self.done()
        print self.path
        if 'vpc' in self.path and 'vrouter' in self.path:
            query=None
            if '?' in self.path:
                query =    urllib.splitquery(self.path)
            key=query[0]+'?'
            param=query[1].split('&') # The property information is parsed and passed to the resource function 
            pdict={}
            for p in param:
                tmp=p.split('=')
                pdict[tmp[0]]=tmp[1]  
            for k in self.router.keys():
                if k in key:
                    self.send(self.router[k](pdict['vpc'],pdict['vrouter'])) # Execution resources 
        elif 'firewall' in self.path:
            self.send(self.router['/firewall']())
        else:
            self.send("{}")
    def basepath(self):
        return "/ins"
    def getrestlet(self):
        rr={}
        rr['/json?']=self.testjson # Registered resources 
        rr['/firewall']=self.firewall
        return rr

            
try:
    server=HTTPServer(('',8084),testjson) # test 2
    server.serve_forever()
except KeyboardInterrupt:
    sys.exit(0)

If you run the above program, you run test 2, and the program listens for 8084.

At this point in your browser's address bar enter http://127.0.0.1:8084/ins/json? VPC = 1 & vrouter = 3

As shown below, I used chrome and installed the plugin.

< img border = 0 id = theimg onclick = window. The open this. (SRC) SRC = "/ / files.jb51.net/file_images/article/201312/20131210094416.png? 2013111094538 ">

Just as a demonstration, the program has many shortcomings. For a good framework, the registered resource should not be in the same class as the resource,

Basepath () and getrestlet () should not be in the implemented resource class (that is, in the test above) and have also disabled router.

You should register in another class so that you can pass different uris and both tests should be able to run. Also is the use of python BaseHTTPServer module, is not suitable for restful.

But that's pretty much how it works, and I'll write a python version of a simple, restful framework some time down the road.


Related articles: