简体   繁体   中英

How do I pass parameters into functions using other functions?

I keep getting error: "unhashable type: list" for line (routing_table[key][0] = [[params], func]. I'm attempting to pass a url and function into a route function. This route function should pick out the parameters for other functions by use of regular expressions. The ultimate goal is to read in "/page/ <page_id> , then pick out <page_id> and replace that with user input. That user input will then be passed into the function. I don't see why this isn't working.

import re

routing_table = {}

def route(url, func):
   key = url
   key = re.findall(r"(.+?)/<[a-zA-Z_][a-zA-Z0-9_]*>", url)
   if key:
      params = re.findall(r"<([a-zA-Z_][a-zA-Z0-9_]*)>", url)
      routing_table[key][0] = [[params], func]
   else:
      routing_table[url] = func

def find_path(url):
   if url in routing_table:
       return routing_table[url]
   else:
      return None

def index():
   return "This is the main page"

def hello():
   return "hi, how are you?"

def page(page_id = 7):
   return "this is page %d" % page_id

def hello():
   return "hi, how are you?"

route("/page/<page_id>", page)

print(routing_table)

I'm not sure why you are using re.findall if you're only interested in the first value found.

Nevertheless, your problem is simply the way you index the result: key is a list, and as the error says, you can't use a list as a dict key. But you've put the [0] outside the first set of brackets, so Python interprets this as you wanting to set the first value of routing_table[key] , rather than you wanting to use the first value of key as the thing to set.

What you actually mean is this:

routing_table[key[0]] = [[params], func]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM