4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Flask:おみくじ。。世界で一番簡単な画像転送Webアプリ♬

Last updated at Posted at 2018-05-22

一番簡単なアプリは、もちろんHelloWorldだけど、。。。
ここでは、画像渡しの一番簡単なアプリ。。。おみくじを作ってみた。

今回は、
①定番のHelloWorld
②画像転送を利用したおみくじアプリ
を作ってみた。

【参考】
1.公式のQuickstart
2.Jinja2の使い方がわかるとFlaskを用いた開発がよりスマートになる
3.Flaskでデータのラベリングサイトを作成する

【コード】

MuAuan/Video-Stream

Flaskは一般的に以下のようなディレクトリ構成をとる。

flask_PJ
├── application.py  :Flaskアプリ
|── templates
|   └── index.html   :表示用html
└── static            :画像ディレクトリ
    └── daikiti 
        └── daikiti.jpg 
        └── tyukiti.jpg 
        └── shokiti.jpg 
        └── suekiti.jpg 
        └── kyo.jpg 
        └── daikyo.jpg
        └── ....jpg

HelloWorld

まず、Helloworld

flask_PJ
├── hello.py
|── templates
    └── index.html(省略) 

なんか動かないとつまらないので、経過時間を表示させました

Hello.py
import flask
import time

app = flask.Flask(__name__)
start_time=time.time()

@app.route('/')  #http://localhost:5000/直下に以下表示
def index():
    return "Hello, World! Passed Time = "+str(int(time.time()-start_time))

if __name__ == '__main__':
    app.run(debug=True)

app.py:ここでは、hello.pyという名称にした
index.html:省略というか無くても表示できる
static:画像無し

@app.route('/') :localhost直下に表示を意味する
表示内容は、以下のとおり
return "Hello, World! Passed Time = "+str(int(time.time()-start_time))
因みに、start_timeはglobal変数としている

おみくじ

flask_PJ
├── daikiti.py
|── templates
|   └── index.html 
└── static
    └── daikiti 
        └── daikiti.jpg 
        └── tyukiti.jpg 
        └── shokiti.jpg 
        └── suekiti.jpg 
        └── kyo.jpg 
        └── daikyo.jpg
        └── ....jpg

daikiti.py:server側本体
index.html:ブラウザ用html
static配下:画像配置(例)

daikiti.py
from flask import Flask, render_template
import glob
from time import time

app = Flask(__name__)

@app.route("/")
def index():
    img_path = glob.glob("static/daikiti/*.jpg")
    return render_template('index.html', img=img_path[int(time()) % 9])
if __name__ == "__main__":
    app.debug = True
    app.run()

①img_path = glob.glob("static/daikiti/*.jpg"):daikitiディレクトリからjpg画像をまとめて取得
②これをrender_templateで時刻を9(枚あるので)で割って、その画像を渡しています。
③app.debug=True:デバッグモードで動かしています。Falseでも動きます。

index.html
<!DOCTYPE html>
<html lang="jp">
<head>
    <meta charset="UTF-8">
    <title>おみくじサイト</title>
</head>
<body>
    <h1>今日のあなたの運勢</h1>
    <img src="{{ img }}" style="width: 300px;">
</body>
</html>

Reloadすれば、ひたすらおみくじが引けます。
そのうち、念願の大吉が。。。

結果

・イメージは、こんなアプリができました!
daikiti.jpg
・RasPiでも動く♬

・静止画アップは出来た、あとカメラ画像の保存ができれば。。。Streaming配信も夢じゃない

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?