Using Python's adorners to solve the problem of user authentication in the bottle framework _python

Source: Internet
Author: User
Tags wrapper

The first is to analyze the requirements, Web program background needs authentication, background page contains multiple pages, the most common way is to add a certification for each URL, but this requires each of the binding URL of the background functions need to add similar or the same code, but this code is excessive redundancy, but not conducive to expansion.

Next we don't talk about adorners, we all know Python is a very powerful language, she can pass functions as arguments to the function, the simplest:

Def p ():
  print ' Hello,world '

def funcfactor (func):
  print ' calling function named ', func.__name__
  func ()
  print ' End '

funcfactor (p)
# Output as:
# calling function named P
# Hello,world
# End

At a glance, define a function P (), pass the function p as a parameter to shout out Funcfactor, and add some action before and after executing the P function.

We can also do this:

Def p ():
  print ' Hello,world '
def funcfactor (func):
  print ' calling function named ', func.__name__
  return func

func = Funcfactor (P)
func ()
# output is:
# calling function named P
hello,world

As you can see, we can return the function and assign it to a variable for later invocation. But in this case we want to do something after the function is executed, but our Python is powerful, python can nest a function in the function, we can do it like this:

Def p ():
  print ' Hello, World '

def Funcfactor (func):
  def wrapper ():
    print ' doing something at start '
    Func ()
    print ' Do something on ' return
  wrapper

func = Funcfactor (P)
func ()
#输出为:
# do Something
at the start # Hello, world # doing something at end


Let's look at the adorner, the code above is a very difficult task to implement, but not elegant enough, and the code does not conform to the philosophy of Python, so the adorner came out, the adorner is not the same as the above principle, the same for wrapping functions, It's just that the code is more elegant and easier to read. The adorner follows the name of the adorner at the beginning of the @ and the next line is the function body to be packaged, and the example above can be implemented using the adorner:

def decorator (func):
  def wrapper ():
    print ' Do something in Start '
    func ()
    print ' Do something ' Return
  wrapper

@decorator
def p ():
  print "Hello, World"

p ()
#输出为:
# do something
at the start # Hello, world # does something at end


In fact, the adorner does not have the performance or other aspects of Ascension, just a syntactic sugar, is the previous example of the rewrite, so much more elegant and reading. If our P () function doesn't want to just lose hello,world, we want to greet certain people we specify:

def decorator (func):
  def wrapper (*args, **kargs):
    print ' Do something at start '
    func (**kargs)
    print ' Do something on ' return
  wrapper

@decorator
def P (name):
  print ' Hello ', name

p (name= "Jim")
#输出为:
# do something in start
# Hello Jim
# do something in end

Adorners are not required to decorate an adorner without parameters, and if the decorated function requires arguments, a function must be nested to handle the arguments. I'm sure everyone knows the usage and function of the adorner. Now back to the point, how to gracefully to the background URL with the validation function? There is no doubt that we use adorners to handle:

def Blog_auth (func):
  '
  define an adorner to decorate the page adorner that needs to
  be validated must be placed under the route adorner
  ' '
  # define wrapper function
  def Wrapper (*args, **kargs):
    try:
      # Read Cookie
      user = Request. cookies[' user '
      shell = Request. cookies[' shell ']
    except:
      # An exception is redirected to the login page
      redirect ('/login ')

    # Verify user data
    if Checkshell Shell):
      # Check Success returns function return
      func (**kargs)
    else:
      # Otherwise redirect to login page
      redirect ('/login ')
  Return wrapper

Add the Blog_auth adorner where you need to verify it again:

@route ('/admin:#/?# ')
@blog_auth
def admin ():
  ""
  used to display the background admin home
  '
  template[' title '] = ' instrument panel | ' + template[' blog_name ']
  template[' user ' = Request. cookies[' user ']
  articles = [] for
  article in Db.posts.find (). Sort ("date", descending). Limit (a):
    Articles.append (article)

  # Send a list of articles to the foreground template
  template[' articles ' = articles return
  TEMPLATE (' admin.html ' , TEMPLATE)

The problem with this bottle verification is gracefully solved with the adorner.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.