I wish to pass an argparse argument to a function with decorators. What is the strategy here? How can I achieve this without global variables?
#!/usr/bin/env python3
from sanic import Sanic, views, response
import os
import argparse
app = Sanic(__name__)
@app.route('/<var:var>')
async def get(self, request, var):
print(path)
return response.text(var)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--path",
help="Set the server root path",
action="store")
args = parser.parse_args()
app.run(host='0.0.0.0', port=8000)
I also tried using the view HTTPMethodView
but without success
Okay so you could dynamically change the function for that route based on the parse arguments... Like this (sorry I'm on my phone)
#!/usr/bin/env python3
from sanic import Sanic, views, response
import os
import argparse
app = Sanic(__name__)
@app.route('/<var:var>')
async def get(self, request, var):
print(path)
return response.text(var)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--path", help="Set the server root path", action="store")
args = parser.parse_args()
def get(var):
# use args.p in your route function!!
app.view_functions["/<var:var>"] = get
app.run(host='0.0.0.0', port=8000)
Might be some mistakes but you should get the gist of it
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.