1

私は人々が彼らの画像をアップロードすることを可能にするウェブサイトに取り組んでいます。これは主に単なる学習体験であり、Pythonで書いています。それができるはずの1つのことは、画像が存在するURLを取得し、それを独自のサーバーに再アップロードすることです。だからここに質問があります:

ある人が私のウェブサイトにURLを与えると、私のサーバーが画像のダウンロードを開始します。その画像をダウンロードしているときに、別のリクエストが届きます。サーバーが何か他のことをしているときでも、サーバーに応答(サーバーがビジーであると言っているように)を与える方法はありますか?これについてもっと良い方法はありますか?

前もって感謝します!

4

1 に答える 1

0

参考になればと思い、例を書きました。これは、urls.txt処理するジョブを一覧表示するファイルと、複数のプロセスを使用してダウンロードする xdownloader.py ファイルで構成されます。Python 2.7 を実行している Linux マシンでテストしました。

xdownloader.py

from multiprocessing import Process
import urllib2

def main():

  try:

    # Read URLs/Destinations from a file
    jobs = []
    with open("urls.txt","r") as ifile:
      for line in ifile:
        jobs.append(line.split(" "))

    # Create a process list to keep track of running processes
    process_list = []
    # Iterate through our jobs list
    for url, save_to in jobs:
      # Create a new process that runs function 'download'
      p = Process(target=download, args=(url, save_to))
      # Save it to a list
      process_list.append(p)
      # Start the process
      p.start()
  except KeyboardInterrupt:
    print("Received keyboard interrupt (ctrl+c). Exiting...")
  finally:
    # Wait for all processes to finish before exiting
    for process in process_list:
       # Wait for this process to finish
       process.join()
    print("All processes finished successfully!")


def download(url, destination):
  # Open a request
  request = urllib2.urlopen(url)
  # Read and save the webpage data to a file
  with open(destination, "w+") as save_file:
    print("Downloading {0}".format(url))
    save_file.write(request.read())

if __name__=="__main__":
  main()

urls.txt

http://google.com google.html
http://yahoo.com yahoo.html
http://news.google.com news.google.html
http://reddit.com reddit.html
http://news.ycombinator.com news.ycombinator.html

実行すると、次のpython xdownloader.pyようになります。

mike@localhost ~ $ python xdownloader.py 
Downloading http://news.ycombinator.com
Downloading http://reddit.com
Downloading http://news.google.com
Downloading http://google.com
Done downloading http://google.com
Done downloading http://news.ycombinator.com
Done downloading http://reddit.com
Downloading http://yahoo.com
Done downloading http://news.google.com
Done downloading http://yahoo.com

ジョブが非同期で実行されていることがわかります...一部のジョブは、他のジョブよりも早く開始されますが、終了は遅くなります。(news.google.com を見ています!) この例がニーズに合わない場合は、コメントでお知らせください。

于 2013-01-16T06:29:02.003 に答える