2016-06-21 118 views
3

我使用django创建了一个web应用程序。不过,我需要一个相同的桌面应用程序,所以我使用了PyQt的webkit。除了文件下载,整个事情都很好。在我的网络应用程序中,服务器在多个地方提供可下载的文件。但是,当单击应用程序的桌面版本中应触发下载的按钮时,什么都不会发生。使用pyqt webkit将django应用程序转换为桌面应用程序

import sys 
from PyQt4.QtCore import * 
from PyQt4.QtGui import * 
from PyQt4.QtWebKit import * 
app = QApplication(sys.argv) 
web = QWebView() 
web.load(QUrl("http://localhost:8000/home")) 
#web.page().setForwardUnsupportedContent(True) 
#web.page().unsupportedContent.connect(save_file_callback) 
web.show() 
sys.exit(app.exec_()) 
+0

这可能有助于http://stackoverflow.com/questions/9194094/download-file-from-qwebkit-at-pyqt –

回答

1
app = QApplication(sys.argv) 
web = QWebView(loadFinished=load_finished) 
web.load(QUrl("http://localhost:8000/home")) 
web.page().setForwardUnsupportedContent(True) 
web.page().unsupportedContent.connect(save_file_callback) 
web.show() 
sys.exit(app.exec_()) 

def save_file_callback(reply): 
    try: 
     with urllib.request.urlopen(reply.url().toString()) as response: 
      with open('downloaded_file.ext', 'wb') as f: 
       f.write(response.read()) 
      except Exception as e: 
       QMessageBox.critical(None, 'Saving Failed!', str(e), QMessageBox.Ok) 

def load_finished(reply): 
    if not reply: 
     QMessageBox.critical(None, 'Error!', 'An error occurred trying to load the page.', QMessageBox.Ok) 

我没有测试的代码,但这个应该让你在正确的道路上。代码是从我最近在webview中运行Django项目的项目中作为桌面应用程序借来的 - https://github.com/awecode/django-runner

+0

can你请解释给save_file_callback的参数?我收到此错误:类型错误:save_file_callback()到底需要2个参数(给定1) 我的Django的代码是: ARG2 = “pathtofile/result321.py” 包装= FileWrapper(文件(ARG2)) 响应= HttpResponse(wrapper,content_type ='application/force-download') response ['Content-Disposition'] ='attachment; filename =“result.py”' response ['Content-Length'] = os.path.getsize(arg2) 返回响应 –

+0

@Code_aholic尝试更新的代码。就像我说的,我没有测试过,我可能在代码中留下了一两个问题。 – xtranophilist

+0

谢谢!很好的工作....我只需要改变代码来使用urllib的urllib2 urllib。 :) –

相关问题