【发布时间】:2014-11-07 20:13:14
【问题描述】:
我正在尝试找到最有效的方法来创建不同的函数名称 myfunction_a ,.. b , c 代码略有不同(输入文件名 'app/data/mydata_a. csv' ) 所以下面是我得到的 a 函数
def myfunction_a(request):
os.getcwd() # Should get this Django project root (where manage.py is)
fn = os.path.abspath(os.path.join(os.getcwd(),'app/data/mydata_a.csv'))
# TODO: Move to helper module
response_data = {}
data_format = 'tsv'
if data_format == 'json':
with open(fn, 'rb') as tsvin:
tsvin = csv.reader(tsvin, delimiter='\t')
for row in tsvin:
print 'col1 = %s col2 = %s' % (row[0], row[1])
response_data[row[0]] = row[1]
result = HttpResponse(json.dumps(response_data), content_type = 'application/json')
else:
with open(fn, 'rb') as tsvin:
buff = tsvin.read()
result = HttpResponse(buff, content_type = 'text/tsv')
return result
我希望能够遍历我的列表并创建多个函数名称:
mylist = ['a','b','c' ... 'z' ]
def myfunction_a(请求): ... ('app/data/mydata_a.csv') 退货要求
得到最终结果:
- def myfunction_a => 采用 'app/data/mydata_a.csv'
- def myfunction_b => 采用 'app/data/mydata_b.csv'
- def myfunction_c => 采用 'app/data/mydata_c.csv'
现在我只是复制并粘贴并更改它。有更好的方法吗?任何建议将不胜感激。谢谢。
【问题讨论】:
-
为什么需要这样做? mywiki.wooledge.org/XyProblem
-
@gnibbler 我在 Django 中使用这个函数名作为 views.py 的一部分,并使用 url 根据需要提取每个函数,从 Django 模板调用视图应用程序。