简体   繁体   English

在Django中,在views.py中执行函数时,进入无限循环

[英]In django on executing a function in views.py , goes into infinite loop

I have a function which uses matplotlib and pandas to crunch tweets from txt file and plot a graph. 我有一个使用matplotlib和pandas从txt文件处理推文并绘制图形的函数。

I'm using that script in views.py in django. 我正在Django的views.py中使用该脚本。 It shows the output correctly the first time, however on executing the webpage second time leads to an infinite loop. 第一次正确显示输出,但是第二次执行网页时将导致无限循环。

I am trying to figure out the reason but can't solve it. 我正在尝试找出原因,但无法解决。 Here is the views.py function: 这是views.py函数:

def main():
    print 'Reading Tweets\n'
    tweets_data_path = 'twitter_data.txt'
    tweets_data = []
    tweets_file = open(tweets_data_path, "r")

    for line in tweets_file:
        try:
            tweet = json.loads(line)
            tweets_data.append(tweet)
        except:
            continue

    print 'Structuring Tweets\n'
    tweets = pd.DataFrame()
    tweets['text'] = map(lambda tweet: tweet['text'], tweets_data)
    tweets['lang'] = map(lambda tweet: tweet['lang'], tweets_data)

    print 'Adding programming languages tags to the data\n'

    tweets['python'] = tweets['text'].apply(
        lambda tweet: word_in_text('python', tweet)
    )
    tweets['javascript'] = tweets['text'].apply(
        lambda tweet: word_in_text('javascript', tweet)
    )
    tweets['ruby'] = tweets['text'].apply(
        lambda tweet: word_in_text('ruby', tweet)
    )

    print 'Analyzing tweets by programming language\n'
    prg_langs = ['python', 'javascript', 'ruby']

    tweets_by_prg_lang = [
        tweets['python'].value_counts()[True],
        tweets['javascript'].value_counts()[True], 
        tweets['ruby'].value_counts()[True]
    ]

    x_pos = list(range(len(prg_langs)))
    width = 0.8
    fig, ax = plt.subplots()
    plt.bar(x_pos, tweets_by_prg_lang, width, alpha=1, color='g')
    ax.set_ylabel('Number of tweets', fontsize=15)
    ax.set_title('Ranking:', fontsize=10, fontweight='bold')
    ax.set_xticks([p + 0.4 * width for p in x_pos])
    ax.set_xticklabels(prg_langs)
    plt.grid()
    plt.show()
return render('analytics.html')

This is the url which calls the main function: 这是调用主要功能的网址:

 url(r'^analytics/$', 'newsletter.analytics.main', name='analytics'),

It executes in terminal as many times as i want. 它在终端中执行任意多次。 But stuck in webpages. 但卡在网页中。 Please shed some light on me !! 请给我一些启示! PS i am new to Django PS我是Django的新手

Your function needs to take the request as an arg & return a response that can be rendered in the browser. 您的函数需要将请求作为arg并返回可以在浏览器中呈现的响应。

Then you'll need to decide how to display it, so essentially you'll need to do; 然后,您需要决定如何显示它,因此从本质上讲,您需要这样做;

def main(request, *args, **kwargs):
    # all your existing code first, then respond to the request;

    canvas = FigureCanvas(fig)
    response= HttpResponse(mimetype='image/png')
    canvas.print_png(response)
    return response

Then for IE support (some versions ignore content_type ), your URL should specify the image extension; 然后,对于IE支持(某些版本会忽略content_type ),您的URL应指定图像扩展名;

url(r'^ analytics/simple.png$', 'newsletter. analytics.main'),

If you want it in a popup or similar, maybe you can then look at creating an ajax response. 如果希望在弹出窗口或类似窗口中显示它,则可以查看创建一个ajax响应。 So instead of returning like that, check for if request.is_ajax: then return something like HttpResponse(json_data, mimetype="application/json") . 因此,不要像这样返回,而是检查if request.is_ajax:然后返回类似HttpResponse(json_data, mimetype="application/json")

I've just seen your edit where you've added the return render('analytics.html') . 我刚刚看到了您在添加return render('analytics.html')地方所做的编辑。 That'll just render the template you've got. 那只会渲染您拥有的模板。 You want to pass context with that so that you can display the data you've processed, or just return an image of what you've processed similar to above. 您希望以此传递上下文,以便可以显示已处理的数据,或者仅返回与上面类似的已处理图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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