小编典典

Python-Flask-在默认浏览器中打开网页

flask

我正在用Python开发一个小项目。它分为两个部分。

第一部分负责爬网并提取一些信息并将其插入数据库。

第二部分负责使用数据库来呈现那些信息。这两部分共享数据库。在第二部分中,我使用Flask框架以一些格式,样式等将信息显示为html,以使其看起来更整洁。

这两部分的源文件都在同一个程序包中,但是要正确运行此程序,用户必须像这样分别运行搜寻器和结果表示器:

python crawler.py

接着

python presenter.py

除了一件事情,一切都还好。我的演示者要做的是创建html格式的结果,并在用户的默认浏览器中打开带有结果的页面,但是它总是被打开两次,可能是由于存在run()方法,该方法在新线程中启动Flask并事情对我来说变得阴沉。我不知道应该怎么做才能使我的presenter.py在运行后仅打开一个选项卡/窗口。

这是我的代码的片段:

from flask import Flask, render_template
import os
import sqlite3


# configuration
DEBUG = True
DATABASE = os.getcwd() + '/database/database.db'

app = Flask(__name__)
app.config.from_object(__name__)
app.config.from_envvar('CRAWLER_SETTINGS', silent=True)



def connect_db():
    """Returns a new connection to the database."""
    try:      
        conn = sqlite3.connect(app.config['DATABASE'])
    return conn
except sqlite3.Error:
    print 'Unable to connect to the database'
    return False


@app.route('/')
def show_entries():
    u"""Loads pages information and emails from the database and
    inserts results into show_entires template. If there is a database
    problem returns error page.
    """
    conn = connect_db()


    if conn:        
    try:            
        cur = connect_db().cursor()

        results = cur.execute('SELECT url, title, doctype, pagesize FROM pages')    
        pages = [dict(url=row[0], title=row[1].encode('utf-8'), pageType=row[2], pageSize=row[3]) for row in results.fetchall()]   


        results = cur.execute('SELECT url, email from emails')
        emails = {}


        for row in results.fetchall():                
            emails.setdefault(row[0], []).append(row[1])                

        return render_template('show_entries.html', pages=pages, emails=emails)

    except sqlite3.Error, e:
        print ' Exception message %s ' % e
        print 'Could not load data from the database!'
        return render_template('show_error_page.html')


else:
    return render_template('show_error_page.html')        


if __name__ == '__main__':
    url = 'http://127.0.0.1:5000'
    webbrowser.open_new(url)
    app.run()

阅读 2351

收藏
2020-04-07

共1个答案

小编典典

我一直在Mac OS X(带有Safari,Firefox和Chrome浏览器)上使用类似的代码,并且运行良好。猜测你可能正在使用Flask的自动重新加载功能。设置debug=False,它将不会尝试自动重新加载。

其他建议,根据我的经验:

  • 考虑随机使用你使用的端口,因为快速的编辑-运行-测试循环有时会发现OS认为端口5000仍在使用中。(或者,如果你同时运行几次代码(例如偶然),则该端口实际上仍在使用中。)
  • 在启动浏览器请求之前,请先让该应用启动一小段时间。我通过调用来做到这一点threading.Timer
    这是我的代码:
import random, threading, webbrowser

port = 5000 + random.randint(0, 999)
url = "http://127.0.0.1:{0}".format(port)

threading.Timer(1.25, lambda: webbrowser.open(url) ).start()

app.run(port=port, debug=False)

(如果需要,这些都在if __name__ == '__main__':或单独的“启动应用”功能下。)

2020-04-07