ラベル Python/Flask の投稿を表示しています。 すべての投稿を表示
ラベル Python/Flask の投稿を表示しています。 すべての投稿を表示

2018-12-20

Flaskを利用した並列処理をThreadを利用する際の忘備録

# スレッド(thread)とは

> プログラムの処理の実行単位
引用:スレッド (thread)とは

# スレッドを複数利用するタイミング


・並列処理を行う必要がある場合

# Pythonで複数Threadを利用する場合



  • Celery
    • ジョブキューを使う
    • redisなど使うため準備が少し必要
  • Thread

import time
import threading

def func1():
    while True:
        print("func1")
        time.sleep(1)


def func2():
    while True:
        print("func2")
        time.sleep(1)


if __name__ == "__main__":
    thread_1 = threading.Thread(target=func1)
    thread_2 = threading.Thread(target=func2)

    thread_1.start()
    thread_2.start()

引用:Pythonの並列・並行処理サンプルコードまとめ


# Flaskで利用する場合



from datetime import datetime
from flask import Flask, make_response
from time import sleep
import threading

app = Flask(__name__)

class MyThread(threading.Thread):
    def __init__(self):
        super(MyThread, self).__init__()
        self.stop_event = threading.Event()

    def stop(self):
        self.stop_event.set()

    def run(self):
        try:
            for _ in range(1000):
                print(f'{datetime.now():%H:%M:%S}')
                sleep(1)

                # 定期的にフラグを確認して停止させる
                if self.stop_event.is_set():
                    break
        finally:
            print('時間のかかる処理が終わりました\n')

jobs = {}

@app.route('/start/<id>/')
def root(id):
    t = MyThread()
    t.start()
    jobs[id] = t
    return make_response(f'{id}の処理を受け付けました\n'), 202

@app.route('/stop/<id>/')
def stop(id):
    jobs[id].stop()
    del jobs[id]
    return make_response(f'{id}の中止処理を受け付けました\n'), 202

@app.route('/status/<id>/')
def status(id):
    if id in jobs:
        return make_response(f'{id}は実行中です\n'), 200
    else:
        return make_response(f'{id}は実行していません\n'), 200


引用:PythonでThreadを使うflaskサンプルを作ってみた

# 並列処理の注意点



  • Flaskのデフォルトでは複数のリクエストを同時に処理することができません。
  • 並列処理を有効にして同時アクセスを可能にするにはthreaded=Trueパラメータを設定します。


引用) Flaskのデフォルトでは同時アクセスを処理できない





2018-04-03

Flaskにおけるredirectとrender_templateメソッドの違い

Flaskでredirectとrender_templateのちがいがよくわからなかったので調べたことまとめ。


2018-01-21

FlaskとAngular JSで{{}}がかぶってエラーが起こるときの対処法

FlaskとAngular JSを利用している際に、エラーが起こる


FlaskでAngular JSを利用して以下のようなHTMLコードを書いているときに、エラーが表示される。


<html ng-app>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
</head>
<body>
  <h1>リダイレクトURL</h1>
  <p>OAuth Providerで登録した、Client IDと、リダイレクトURLを入力してください。</p>
  <form>
    <label for="client_id">クライアントID</label>
    <input type="textfield" name="client_id" id="client_id" ng-model="client_id" placeholder="クライアントID"></input>
    <label for="redirect_uri">リダイレクトURL</input>
    <input type="textfield" name="redirect_uri" id="redirect_uri" ng-model="redirect_uri" placeholder="リダイレクトURL"></input>
    <label for="textfield">スコープ</label>
    <input type="textfield" name="scope" id="scope" ng-model="scope" placeholder="scope"></input>
  </form>
  <p>生成されたURL</p>
    <a href="https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=263680507619-6sm2e6jv584ilmd7h6jrn5dstk6magke.apps.googleusercontent.com&redirect_uri=http://127.0.0.1:5000/callback.html/&scope=https://www.googleapis.com/auth/calendar
">これじゃ</a>
    <p>{{client_id + redirect_uri + scope}} </p>
  {% if result %}
  <h1>アクセストークン</h1>
    <form method="post">
      <label>Access Token</label>
      <blockquote>{{ result }}</blockquote>
      <input type="textfield" name="access_token" value="{{result}}">
      <input type="submit"></input>
  </form>
  {% endif %}

  {% if schedule %}
  <h1>スケジュール一覧</h1>
  <blockquote>{{ schedule }}</blockquote>
  {% endif %}

<!-- javascript-->
<script>
</script>
</body>
</html>


jinja2.exceptions.UndefinedError
jinja2.exceptions.UndefinedError: 'client_id' is undefined


注目の投稿

めちゃくちゃ久しぶりにこのブログ書いたw 更新3年ぶりw > 多様性というゲームは尊厳と自由を勝ち取るゲームなのかもしれないな。  もともとツイッターでツイートした内容なんだけど、ちょっと深ぼる。 ----- 自分は男 x 30代x 二児の父 x 経営者 x 都心(共働き世...