2016-09-21 147 views
0

我有一個小型django項目,我試圖從我的views.py中傳遞一個變量到tasks.py並使用該變量運行一個任務,但我得到的名稱不是定義的錯誤,我已經嘗試了許多解決方案,我見過的其他問題,但我似乎無法得到它的工作NameError:未定義全局名稱'query'

這裏是我的views.py

# -*- coding: utf-8 -*- 
from __future__ import unicode_literals 
from django.shortcuts import render, loader 
from django.template import Context 
from django.http import HttpResponse 
import json 
import requests 
from tasks import rti 

def index(request): 
    return render(request, 'bus/index.html') 

def search(request): 
    query = request.GET.get('q') 
    t = loader.get_template('bus/search.html') 
    c = Context({ 'query': query,}) 
    rti() 
    return HttpResponse(t.render(c)) 

這裏是我的tasks.py

from background_task import background 
import time 


@background(schedule=1) 
def rti(): 
    timeout = time.time() + 60 * 15 
    while time.time() < timeout: 
     from views import search 
     dblink = '*apiurl*' + str(query) + '&format=json' 
     savelink = 'bus/static/bus/stop' + str(query)+ '.json' 
     r = requests.get(dblink) 
     jsondata = json.loads(r.text) 
     with open(savelink, 'w') as f: 
      json.dump(jsondata, f) 

這裏是追溯:

Traceback (most recent call last): 
    File "/Users/dylankilkenny/dev/python/test2/lib/python2.7/site-packages/background_task/tasks.py", line 49, in bg_runner 
    func(*args, **kwargs) 
    File "/Users/dylankilkenny/dev/python/test2/mysite/bus/tasks.py", line 9, in rti 
    from views import search 
NameError: global name 'query' is not defined 

回答

0

你必須改變你的方法的定義,以def rti(query):,並考慮rti(query)使用它,因爲你的後臺任務不知道里面查詢變量什麼。

0

您需要修改您的任務,以便將查詢作爲參數。

@background(schedule=1) 
def rti(query): 
    ... 

,當你調用任務在你看來

rti(query) 
+0

香港專業教育學院嘗試這樣做,得到這個錯誤:'類型錯誤:RTI()不帶任何參數(1給出)' –

+0

這聽起來好像該方法尚未更新爲「def rti(query)」。確保您已重新啓動正在運行任務的進程。 – Alasdair

0

你沒有通過任何參數的方法rti()已呼叫內views.py然後通過查詢。爲此,在定義中的方法rti()時,該方法應該採用查詢之類的參數。之後,您將可以在rti()內使用query

請按照下列:

tasks.py:

@background(schedule=1) 
def rti(query): 
    {...your code} 

views.py:

def search(request): 
    query = request.GET.get('q') 
    t = loader.get_template('bus/search.html') 
    c = Context({ 'query': query,}) 
    rti(query)  #calling rti from tasks.py passing the argument 
    return HttpResponse(t.render(c)) 
相關問題