溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

web開發(fā)中如何使用request method過濾

發(fā)布時間:2021-10-18 14:07:00 來源:億速云 閱讀:109 作者:小新 欄目:編程語言

這篇文章將為大家詳細講解有關web開發(fā)中如何使用request method過濾,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

request method過濾:

一般來說,即便是同一個url,因為請求方法不同,處理方式也不同;

如一url,GET方法返回網(wǎng)頁內(nèi)容,POST方法browser提交數(shù)據(jù)過來需要處理,并存入DB,最終返回給browser存儲成功或失??;

即,需請求方法和正則同時匹配才能決定執(zhí)行什么處理函數(shù);

GET,請求指定的頁面信息,并返回header和body;

HEAD,類似GET,只不過返回的響應中只有header沒有body;

POST,向指定資源提交數(shù)據(jù)進行處理請求,如提交表單或上傳文件,數(shù)據(jù)被包含在請求正文中,POST請求可能會導致新的資源的建立和已有資源的修改;

PUT,從c向s傳送的數(shù)據(jù)取代指定的文檔內(nèi)容,MVC框架中或restful開發(fā)中常用;

DELETE,請求s刪除指定的內(nèi)容;

注:

s端可只支持GET、POST,其它HEAD、PUT、DELETE可不支持;

ver1:

例:

from wsgiref.simple_server import make_server

from webob import Request, Response, dec, exc

import re

class Application:

    # ROUTE_TABLE = {}

    ROUTE_TABLE = []   #[(method, re.compile(pattern), handler)]

    GET = 'GET'

    @classmethod

    def register(cls, method, pattern):

        def wrapper(handler):

            cls.ROUTE_TABLE.append((method, re.compile(pattern), handler))

            return handler

        return wrapper

    @dec.wsgify

    def __call__(self, request:Request) -> Response:

        for method, regex, handler in self.ROUTE_TABLE:

            if request.method.upper() != method:

                continue

            if regex.match(request.path):   #同if regex.search(request.path)

                return handler(request)

        raise exc.HTTPNotFound()

@Application.register(Application.GET, '/python$')   #若非要寫成@Application.register('/python$'),看下例

def showpython(request):

    res = Response()

    res.body = '<h2>hello python</h2>'.encode()

    return res

@Application.register('post', '^/$')

def index(request):

    res = Response()

    res.body = '<h2>welcome</h2>'.encode()

    return res

if __name__ == '__main__':

    ip = '127.0.0.1'

    port = 9999

    server = make_server(ip, port, Application())

    try:

        server.serve_forever()

    except Exception as e:

        print(e)

    finally:

        server.shutdown()

        server.server_close()

VER2:

例:

from wsgiref.simple_server import make_server

from webob import Request, Response, dec, exc

import re

class Application:

    # ROUTE_TABLE = {}

    ROUTE_TABLE = []   #[(method, re.compile(pattern), handler)]

    GET = 'GET'

    @classmethod

    def route(cls, method, pattern):

        def wrapper(handler):

            cls.ROUTE_TABLE.append((method, re.compile(pattern), handler))

            return handler

        return wrapper

    @classmethod

    def get(cls, pattern):

        return cls.route('GET', pattern)

    @classmethod

    def post(cls, pattern):

        return cls.route('POST', pattern)

    @classmethod

    def head(cls, pattern):

        return cls.route('HEAD', pattern)

    @dec.wsgify

    def __call__(self, request:Request) -> Response:

        for method, regex, handler in self.ROUTE_TABLE:

            print(method, regex, handler)

            if request.method.upper() != method:

                continue

            matcher = regex.search(request.path)

            print(matcher)

            if matcher:   #if regex.search(request.path)

                return handler(request)

        raise exc.HTTPNotFound()

@Application.get('/python$')

def showpython(request):

    res = Response()

    res.body = '<h2>hello python</h2>'.encode()

    return res

@Application.post('^/$')

def index(request):

    res = Response()

    res.body = '<h2>welcome</h2>'.encode()

    return res

if __name__ == '__main__':

    ip = '127.0.0.1'

    port = 9999

    server = make_server(ip, port, Application())

    try:

        server.serve_forever()

    except Exception as e:

        print(e)

    finally:

        server.shutdown()

        server.server_close()

VER3:

例:

一個url可設置多個方法:

思路1:

如果什么方法都不寫,相當于所有方法都支持;

@Application.route('^/$')相當于@Application.route(None,'^/$')

如果一個處理函數(shù)需要關聯(lián)多個請求方法,這樣寫:

@Application.route(['GET','PUT','DELETE'],'^/$')

@Application.route(('GET','PUT','POST'),'^/$')

@Application.route({'GET','PUT','DELETE'},'^/$')

思路2:

調(diào)整參數(shù)位置,把請求方法放到最后,變成可變參數(shù):

def route(cls,pattern,*methods):

methods若是一個空元組,表示匹配所有方法;

methods若是非空,表示匹配指定方法;

@Application.route('^/$','POST','PUT','DELETE')

@Application.route('^/$')相當于@Application.route('^/$','GET','PUT','POST','HEAD','DELETE')

例:

from wsgiref.simple_server import make_server

from webob import Request, Response, dec, exc

import re

class Application:

    # ROUTE_TABLE = {}

    ROUTE_TABLE = []   #[(method, re.compile(pattern), handler)]

    GET = 'GET'

    @classmethod

    def route(cls, pattern, *methods):

        def wrapper(handler):

            cls.ROUTE_TABLE.append((methods, re.compile(pattern), handler))

            return handler

        return wrapper

    @classmethod

    def get(cls, pattern):

        return cls.route(pattern, 'GET')

    @classmethod

    def post(cls, pattern):

        return cls.route(pattern, 'POST')

    @classmethod

    def head(cls, pattern):

        return cls.route(pattern, 'HEAD')

    @dec.wsgify

    def __call__(self, request:Request) -> Response:

        for methods, regex, handler in self.ROUTE_TABLE:

            print(methods, regex, handler)

            if not methods or request.method.upper() in methods:   #not methods,即所有請求方法

                matcher = regex.search(request.path)

                print(matcher)

                if matcher:

                    return handler(request)

        raise exc.HTTPNotFound()

@Application.get('/python$')

def showpython(request):

    res = Response()

    res.body = '<h2>hello python</h2>'.encode()

    return res

@Application.route('^/$')   #支持所有請求方法,結合__call__()中not methods

def index(request):

    res = Response()

    res.body = '<h2>welcome</h2>'.encode()

    return res

if __name__ == '__main__':

    ip = '127.0.0.1'

    port = 9999

    server = make_server(ip, port, Application())

    try:

        server.serve_forever()

    except Exception as e:

        print(e)

    finally:

        server.shutdown()

        server.server_close()

關于“web開發(fā)中如何使用request method過濾”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

web
AI