Question

I need help with the following When you run it like the following: python3 decorator.py CrocodileLikesStrawberries...

I need help with the following

When you run it like the following:

python3 decorator.py CrocodileLikesStrawberries
The token "CrocodileLikesStrawberries" allows you to interact with the functions.

This code is OK, but there is repetition with the checks for auth_token. We could pull this out into it's own function, but what is even better design is to use a decorator. Create an authorise decorator and use it with the refactored code given below.

import sys

MESSAGE_LIST = []

@authorise
def get_messages():
return MESSAGE_LIST

@authorise
def add_messages(msg):
global MESSAGE_LIST
MESSAGE_LIST.append(msg)

if __name__ == '__main__':
auth_token = ""
if len(sys.argv) == 2:
auth_token = sys.argv[1]

add_messages(auth_token, "Hello")
add_messages(auth_token, "How")
add_messages(auth_token, "Are")
add_messages(auth_token, "You?")
print(get_messages(auth_token))

0 0
Add a comment Improve this question Transcribed image text
Answer #1

import sys

MESSAGE_LIST = []
auth_token = ""

def authorise(func):
def validate_token():
global auth_token
"""
Here you can write validation code for token
if(auth_token!="CrocodileLikesStrawberries"):
"""

validate_token()
return func

  
def get_messages():
return MESSAGE_LIST

def add_messages(msg):
global MESSAGE_LIST
MESSAGE_LIST.append(msg)

if __name__ == '__main__':
  
if len(sys.argv) == 2:
global auth_token
auth_token = sys.argv[1]

authorise(add_messages( "Hello"))
authorise(add_messages("How"))
authorise(add_messages("Are"))
authorise(add_messages("You?"))
print(authorise(get_messages()))

----------------------------------------------------------------------------------------------------------------------------------------------------------------------

authorise here acts as the required decorator. func calls the method passed as the argument (like add_messages). return func helps in using get_messages calls using authorise. For every call using authorise, validate_token will be called which can be used for token identification. This validation can be put out of decorator and called once using the func reference similar to add_messages.

Add a comment
Know the answer?
Add Answer to:
I need help with the following When you run it like the following: python3 decorator.py CrocodileLikesStrawberries...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I need help ASAP on this, this is due at midnight PST. This is the current...

    I need help ASAP on this, this is due at midnight PST. This is the current code I have. How can I allow the user to quit. My counting while loop works fine, but I would like it to not keep outputting username if a file was successfully opened. This is what is required. Prompt You have assumed the role of managing the technology infrastructure at a zoo. You will develop a working program (either an authentication system or a...

  • need help to complete the task: app.py is the Python server-side application. It includes a class...

    need help to complete the task: app.py is the Python server-side application. It includes a class for representing the list of albums. You need to complete the missing parts such that it loads data from the data/albums.txt and data/tracks.txt files. You can decide what internal data structure you want to use for storing the data. It is already implemented that a single instance of the Albums class is used, so that loading from the files happens only once (and not...

  • 12p I need help this is Python EXCEPTIONS: It's easier to ask forgiveness than permission. Try...

    12p I need help this is Python EXCEPTIONS: It's easier to ask forgiveness than permission. Try the code and catch the errors. The other paradigm is 'Look before you leap' which means test conditions to avoid errors. This can cause race conditions. 1.Write the output of the code here: class MyError(Exception): pass def notZero(num): if num == 0: raise MyError def run(f): try: exec(f) except TypeError: print("Wrong type, Programmer error") except ValueError: print("We value only integers.") except Zero Division Error:...

  • Please answer this question using python programming only and provide a screen short for this code....

    Please answer this question using python programming only and provide a screen short for this code. Homework 3 - Multiples not less than a number Question 1 (out of 3) This homework is a SOLO assignment. While generally I encourage you to help one another to learn the material, you may only submit code that you have composed and that you understand. Use this template to write a Python 3 program that calculates the nearest multiple of a number that...

  • Hey I have a task which consists of two part. Part A asks for writing a...

    Hey I have a task which consists of two part. Part A asks for writing a program of WORD & LINE CONCORDANCE APPLICATION in python which I have completed it. Now the second part has given 5 dictionary implementation codes namely as: (ChainingDict, OpenAddrHashDict with linear probing, OpenAddrHashDict with quadratic probing, and 2 tree-based dictionaries from lab 12 (BST-based dictionary implementation) and asks for my above program WORD & LINE CONCORDANCE APPLICATION  to use these implemented code and show the time...

  • My Python file will not work below and I am not sure why, please help me...

    My Python file will not work below and I am not sure why, please help me debug! ********************************* Instructions for program: You’ll use these functions to put together a program that does the following: Gives the user sentences to type, until they type DONE and then the test is over. Counts the number of seconds from when the user begins to when the test is over. Counts and reports: The total number of words the user typed, and how many...

  • In this part, you will complete the code to solve a maze.

    - Complete the code to solve a maze- Discuss related data structures topicsProgramming-----------In this part, you will complete the code to solve a maze.Begin with the "solveMaze.py" starter file.This file contains comment instructions that tell you where to add your code.Each maze resides in a text file (with a .txt extension).The following symbols are used in the mazes:BARRIER = '-' # barrierFINISH = 'F' # finish (goal)OPEN = 'O' # open stepSTART = 'S' # start stepVISITED = '#' #...

  • could you please help me with this problem, also I need a little text so I...

    could you please help me with this problem, also I need a little text so I can understand how you solved the problem? import java.io.File; import java.util.Scanner; /** * This program lists the files in a directory specified by * the user. The user is asked to type in a directory name. * If the name entered by the user is not a directory, a * message is printed and the program ends. */ public class DirectoryList { public static...

  • In java language here is my code so far! i only need help with the extra...

    In java language here is my code so far! i only need help with the extra credit part For this project, you will create a Rock, Paper, Scissors game. Write a GUI program that allows a user to play Rock, Paper, Scissors against the computer. If you’re not familiar with Rock, Paper, Scissors, check out the Wikipedia page: http://en.wikipedia.org/wiki/Rock-paper-scissors This is how the program works: The user clicks a button to make their move (rock, paper, or scissors). The program...

  • You need not run Python programs on a computer in solving the following problems. Place your...

    You need not run Python programs on a computer in solving the following problems. Place your answers into separate "text" files using the names indicated on each problem. Please create your text files using the same text editor that you use for your .py files. Answer submitted in another file format such as .doc, .pages, .rtf, or.pdf will lose least one point per problem! [1] 3 points Use file math.txt What is the precise output from the following code? bar...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT