Python - Flask - 在默认浏览器中打开一个网页 [英] Python - Flask - open a webpage in default browser

查看:1711
本文介绍了Python - Flask - 在默认浏览器中打开一个网页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

第二部分是用于使用数据库来呈现这些信息的resposible。
两部分共享数据库。在第二部分中,我使用Flask框架将信息显示为具有某些格式,样式等的html,以使其看起来更清晰。



这两个部分的源文件都在相同的软件包,但为了正确运行这个程序,用户必须像这样分别运行抓取程序和结果展示器:


$ b

python crawler.py



然后是

python presenter.py



除了一件事以外,一切都是正确的。我主要做的是以html格式创建结果,并在用户的默认浏览器中打开结果页面,但总是打开两次,可能是由于run()方法的存在,Flask在新线程中启动,事情变得对我阴天。我不知道该怎么做才能让我的presenter.py在运行后只打开一个标签页/窗口。



这是我的代码片段代码:

  from flask import Flask,render_template 
import os
import sqlite3

$ b $配置
DEBUG = True
DATABASE = os.getcwd()+'/database/database.db'

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


$ b def connect_db()
返回到数据库的新连接。
try:
conn = sqlite3.connect(app.config ['DATABASE'])
return conn
除了sqlite3.Error:
print'无法连接数据库'
return False


@ app.route('/')
def show_entries():
u从数据库加载页面信息和电子邮件,
将结果插入到show_entires templ吃了。如果有数据库
问题返回错误页面。

conn = connect_db()


如果conn:
try:
cur = connect_db()。cursor()

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


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


for results.fetchall():
emails.setdefault(row [0] ,[]]。append(row [1])$ ​​b
$ b return render_template('show_entries.html',pages = pages,emails = emails)

除sqlite3.Error外, e:
print'Exception message%s'%e
print'无法从数据库加载数据!'
return render_template('show_error_page.html')


其他:
返回render_template('show_error_page.html')


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


解决方案

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

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


  • 考虑随机化您使用的端口,因为快速编辑 - 运行 - 测试循环有时会发现操作系统认为端口5000仍在使用中。 (或者,如果您同时运行代码几次,意外地说,这个端口确实还在使用中。)

  • 在启动浏览器之前给应用程序一段时间的启动请求。我通过调用 threading.Timer 来实现。



这是我的代码:

  import random,threading,webbrowser 
$ b $ port = 5000 + random.randint(0,999)
url =http://127.0.0.1:{0}\".format(port)

threading.Timer(1.25,lambda:webbrowser.open(url)).start()
$ b app.run(port = port,debug = False)

如果__name__ =='__main __':,或者在一个单独的启动应用程序函数中,如果你愿意的话,这些都在之下。)


I am working on a small project in Python. It is divided into two parts.

First part is responsible to crawl the web and extract some infromation and insert them into a database.

Second part is resposible for presenting those information with use of the database. Both parts share the database. In the second part I am using Flask framework to display information as html with some formatting, styling and etc. to make it look cleaner.

Source files of both parts are in the same package, but to run this program properly user has to run crawler and results presenter separately like this :

python crawler.py

and then

python presenter.py

Everything is allright just except one thing. What I what presenter to do is to create result in html format and open the page with results in user's default browser, but it is always opened twice, probably due to the presence of run() method, which starts Flask in a new thread and things get cloudy for me. I don't know what I should do to be able to make my presenter.py to open only one tab/window after running it.

Here is the snippet of my code :

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()

解决方案

I use similar code on Mac OS X (with Safari, Firefox, and Chrome browsers) all the time, and it runs fine. Guessing you may be running into Flask's auto-reload feature. Set debug=False and it will not try to auto-reload.

Other suggestions, based on my experience:

  • Consider randomizing the port you use, as quick edit-run-test loops sometimes find the OS thinking port 5000 is still in use. (Or, if you run the code several times simultaneously, say by accident, the port truly is still in use.)
  • Give the app a short while to spin up before you start the browser request. I do that through invoking threading.Timer.

Here's my code:

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)

(This is all under the if __name__ == '__main__':, or in a separate "start app" function if you like.)

这篇关于Python - Flask - 在默认浏览器中打开一个网页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆