• Skip to main content
  • Skip to primary sidebar

学習記録

Flaskをdigitalocean(ubuntu18)にインストール

2018年10月9日 by 河副 太智 Leave a Comment

■Puttyから以下のコードをひたすら入力

digitaloceanのputty解説

add-apt-repositoryについて解説

sudo apt-get install apt-file
apt –fix-broken install
sudo apt-file update
sudo apt-file search add-apt-repository ## これはなくてもいい?
sudo apt-get install software-properties-common
sudo apt-get update && sudo apt-get upgrade
sudo apt-get install apache2 mysql-client mysql-server
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update

 

■python3.6をインストール

pipで迷ったらここ

sudo add-apt-repository ppa:jonathonf/python-3.6
sudo apt-get update
sudo apt-get install python3.6 python3.6-dev
wget https://bootstrap.pypa.io/get-pip.py
sudo python3.6 get-pip.py
python3.6 –version
apt install python3-pip
pip3.6 install mod_wsgi
sudo apt-get install apache2 apache2-dev
pip3.6 install mod_wsgi

 

■文字列のコピー作業

以下のコードを打ち込むと
mod_wsgi-express module-config

以下のような文字列が出てくるのでコピーする(例)

LoadModule wsgi_module “/usr/local/lib/python3.6/dist-packages/mod_wsgi/server/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so”
WSGIPythonHome “/usr”

 

nano /etc/apache2/mods-available/wsgi.load
nanoで上記文字列を張り付ける

 

■Flaskのインストール

a2enmod wsgi
service apache2 restart
pip3.6 install Flask

 

■文字列のコピー作業2

nano /etc/apache2/sites-available/FlaskApp.conf
nanoでconfファイルを開く

 

以下を張り付けるIPアドレスだけは変更する

1
2
3
4
5
6
7
8
9
10
11
12
<VirtualHost *:80>
                ServerName 192.168.0.1
                ServerAdmin youremail@email.com
                WSGIScriptAlias / /var/www/FlaskApp/FlaskApp.wsgi
                <Directory /var/www/FlaskApp/FlaskApp/>
                        Order allow,deny
                        Allow from all
                </Directory>
                ErrorLog ${APACHE_LOG_DIR}/FlaskApp-error.log
                LogLevel warn
                CustomLog ${APACHE_LOG_DIR}/FlaskApp-access.log combined
</VirtualHost>

 

■FlaskAppフォルダを作成

sudo a2ensite FlaskApp
service apache2 reload

mkdir /var/www/FlaskApp
cd /var/www/FlaskApp
nano FlaskApp.wsgi
以下を張り付ける

1
2
3
4
5
6
7
#!/usr/bin/python3.6
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/FlaskApp/")
 
from FlaskApp import app as application

 

mkdir FlaskApp cd FlaskApp

nano __init__.py
以下を張り付ける

1
2
3
4
5
6
7
8
9
10
11
from flask import Flask
import sys
 
app = Flask(__name__)
 
@app.route('/')
def homepage():
    return "Hi there, how ya doin?"
 
if __name__ == "__main__":
    app.run()

 

■python実行

cd /var/www/FlaskApp/FlaskApp
python3.6 __init__.py

service apache2 reload

でブラウザからIPアドレスを打ち込む

 

以下のように表示される

 

 

FTPでの見え方

 

 

 

 

ルーティング

 

■ディレクトリ(URL)を指定

以下のようにディレクトリ下にプログラムを配置する場合はhttp://128.199.64.242/abc

@app.route(“/abc”)というようにスラッシュ以下に
ディレクトリ名を任意に入力する。

1
2
3
4
5
6
7
8
9
10
11
from flask import Flask
import sys
 
app = Flask(__name__)
 
<span style="background-color: #ff0000;">@app.route('/abc')</span>
def homepage():
    return "こんばんは"
 
if __name__ == "__main__":
    app.run()

 

■複数のページを作成する
@app.routeとdefをそれぞれ作成すると指定したディレクトリ名のURLにて
異なるページを表示する事ができる

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from flask import Flask
import sys
 
app = Flask(__name__)
 
<span style="color: #000000; background-color: #ff0000;">@app.route('/abc')</span>
<span style="background-color: #3366ff;">def homepage():</span>
    return "こんばんは"
 
<span style="background-color: #ff0000;">@app.route('/def')</span>
<span style="background-color: #3366ff;">def aaa():</span>
    return "こんにちは"
 
if __name__ == "__main__":
    app.run()

■動的URLページを作成する
@app.routeの後にディレクトリ名と<name>を記述し、
defの引数にnameを指定する

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from flask import Flask
import sys
 
app = Flask(__name__)
 
<span style="color: #000000;">@app.route('/')</span>
def index():
    return "こんばんは"
 
@app.route('/bbb/<name>')
def bbb(name):
    return "This is a page for {}".format(name)
 
if __name__ == "__main__":
    app.run()

参考

 

render_templateによる読み込み

上記のままでは複数のページを作成した場合にinitがごちゃごちゃに
なってしまうので、各htmlページを用意し、URLごとに設定した
htmlに飛ぶように設定するにはrender_templeteを使用

※from flask import Flask,render_templateと記述

1
2
3
4
5
6
7
8
9
10
from flask import Flask,render_template
app = Flask(__name__)
@app.route('/')
def index():
    return render_template('index.html', message="花子さん")
if __name__ == "__main__":
    app.run()

参考

参考

 

Filed Under: VPS

jsonファイルから情報を取得

2018年10月3日 by 河副 太智 Leave a Comment

Comtradeの国名一覧jsonファイルから国名を取得します。

1
2
url = urllib.request.urlopen("https://comtrade.un.org/data/cache/partnerAreas.json")
jdata = json.loads(url.read().decode())

jsonファイルのデータを個別に指定して変数に代入

1
reporting_area = "&r=" + (jdata['results'][i]["id"])

i はfor文のiです。

Filed Under: python3

Dashで複数のインプット

2018年10月1日 by 河副 太智 Leave a Comment

複数のドロップダウンメニューを設置して
それぞれの選択項目によってグラフが変わるパターンを紹介します。

 

 

 

コード

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.graph_objs as go
import pandas as pd
 
df = pd.read_csv('mpg.csv')
 
app= dash.Dash()
features = df.columns
 
app.layout = html.Div([
    html.Div([
        dcc.Dropdown(id="xaxis",options=[{"label":i,"value":i}for i in features],value="displacement")
    ],style={"width":"48%","display":"inline-block"}),
    html.Div([
        dcc.Dropdown(id="yaxis",options=[{"label":i,"value":i}for i in features],value="mpg")
    ],style={"width":"48%","display":"inline-block"}),
    dcc.Graph(id="feature-graphic")
],style={"padding":10})
 
@app.callback(Output("feature-graphic","figure"),
             [Input("xaxis","value"),
             Input("yaxis","value")])
 
 
def update_graph(xaxis_name,yaxis_name):
    return{"data":[go.Scatter(x=df[xaxis_name],
                             y=df[yaxis_name],
                             text=df["name"],
                             mode="markers",
                             marker={"size":15,
                                    "opacity":0.5,
                                    "line":{"width":0.5,"color":"white"}})
                             ]
           ,"layout":go.Layout(title="My Dashboard for MPG",
          xaxis={"title":xaxis_name},
          yaxis={"title":yaxis_name},
                              hovermode="closest"),
          }
 
if __name__ == '__main__':
    app.run_server()

 

Filed Under: Dash

Dashでドロップダウンメニュー

2018年9月28日 by 河副 太智 Leave a Comment

Dashでドロップダウンメニューを設定します。

使用データは世界各国のGDP、寿命、人口データです。
csvデータ:gapminderDataFiveYear

 

ドロップダウンメニューは「年」を選択し、
各年度ごとのグラフが表示されるようにします。

1
2
3
4
5
6
7
8
year_options = []
for year in df['year'].unique():
    year_options.append({'label':str(year),'value':year})
 
app.layout = html.Div([
    dcc.Graph(id='graph'),
    dcc.Dropdown(id='year-picker',options=year_options,value=df['year'].min())
])

データフレームに格納した後、yearカラムを.unique()で分別します。
これは重複する年度があるためです。

次にコールバックでドロップダウンメニューにて選択された値に応じた
データ表示の詳細を設定します。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@app.callback(Output('graph', 'figure'),
              [Input('year-picker', 'value')])
def update_figure(selected_year):
    filtered_df = df[df['year'] == selected_year]
    traces = []
    for continent_name in filtered_df['continent'].unique():
        df_by_continent = filtered_df[filtered_df['continent'] == continent_name]
        traces.append(go.Scatter(
            x=df_by_continent['gdpPercap'],
            y=df_by_continent['lifeExp'],
            text=df_by_continent['country'],
            mode='markers',
            opacity=0.7,
            marker={'size': 15},
            name=continent_name
        ))
 
    return {
        'data': traces,
        'layout': go.Layout(
            xaxis={'type': 'log', 'title': 'GDP Per Capita'},
            yaxis={'title': 'Life Expectancy'},
            hovermode='closest'
        )
    }

コールバックを使用してドロップダウンメニューを選べばすぐに
関数の内容が実行されます。
returnで帰ってきた値がグラフに反映されます。

 

実行結果:

 

 

 

 

コード全体:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.graph_objs as go
import pandas as pd
 
df = pd.read_csv('gapminderDataFiveYear.csv')
 
 
 
app = dash.Dash()
 
 
# # https://dash.plot.ly/dash-core-components/dropdown
# # We need to construct a dictionary of dropdown values for the years
year_options = []
for year in df['year'].unique():
    year_options.append({'label':str(year),'value':year})
 
app.layout = html.Div([
    dcc.Graph(id='graph'),
    dcc.Dropdown(id='year-picker',options=year_options,value=df['year'].min())
])
 
@app.callback(Output('graph', 'figure'),
              [Input('year-picker', 'value')])
def update_figure(selected_year):
    filtered_df = df[df['year'] == selected_year]
    traces = []
    for continent_name in filtered_df['continent'].unique():
        df_by_continent = filtered_df[filtered_df['continent'] == continent_name]
        traces.append(go.Scatter(
            x=df_by_continent['gdpPercap'],
            y=df_by_continent['lifeExp'],
            text=df_by_continent['country'],
            mode='markers',
            opacity=0.7,
            marker={'size': 15},
            name=continent_name
        ))
 
    return {
        'data': traces,
        'layout': go.Layout(
            xaxis={'type': 'log', 'title': 'GDP Per Capita'},
            yaxis={'title': 'Life Expectancy'},
            hovermode='closest'
        )
    }
 
if __name__ == '__main__':
    app.run_server()

 

Filed Under: Dash

Dashのコールバック

2018年9月28日 by 河副 太智 Leave a Comment

Dashのコールバックを使ってテキストフィールドに入力された
値を別の場所にリアルタイムに表示してみます。

 

レイアウトを以下のように設定し、インプットするフォームに
“my-id”と名前を付けます。
また、空のhtmlフィールドを用意して”my-div”と名前を付けます。

1
2
3
4
5
app.layout = html.Div([
    dcc.Input(id="my-id",value="Inisitoa Text",type="text"),
    html.Div(id="my-div")
    
])

 

次にコールバックの設定です。

1
2
3
4
@app.callback(Output(component_id="my-div",component_property="children"),
             [Input(component_id="my-id",component_property="value")])
def updata_output_div(input_value):
    return "You enterd:{}".format(input_value)

Output、つまり出力先は先ほど指定したhtmlの空フィールド”my-div”に
向けているのでテキスト入力フォームの直下にアウトプットされた値が
表示されるという意味になります。

Inputはdcc.Input()で設定した”my-id”から来たものがインプットである
と定義します。

 

このように設定すると表示されたテキストフォームに文字列を
入力すると、フォーム直下の空htmlフィールドに入力した文字列が
即座に反映されます。

 

 

コード

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input,Output
 
app = dash.Dash()
 
app.layout = html.Div([
    dcc.Input(id="my-id",value="Inisitoa Text",type="text"),
    html.Div(id="my-div")
    
])
 
@app.callback(Output(component_id="my-div",component_property="children"),
             [Input(component_id="my-id",component_property="value")])
def updata_output_div(input_value):
    return "You enterd:{}".format(input_value)
 
 
if __name__ == '__main__':
    app.run_server()

 

 

Filed Under: Dash

DashでMarkdown

2018年9月26日 by 河副 太智 Leave a Comment

Markdownを記述すると簡単にhtml文書構成ができます。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import dash
import dash_html_components as html
 
app = dash.Dash()
 
text = '''
あいうえお
かきくけこ
さしすせそ
[links](https://commonmark.org/help/)
'''
 
app.layout = html.Div([
            dcc.Markdown(children=text)
])
 
if __name__ == '__main__':
    app.run_server()    

 

Filed Under: Dash

  • « Go to Previous Page
  • Page 1
  • Interim pages omitted …
  • Page 12
  • Page 13
  • Page 14
  • Page 15
  • Page 16
  • Interim pages omitted …
  • Page 66
  • Go to Next Page »

Primary Sidebar

カテゴリー

  • AWS
  • Bootstrap
  • Dash
  • Django
  • flask
  • GIT(sourcetree)
  • Plotly/Dash
  • VPS
  • その他tool
  • ブログ
  • プログラミング
    • Bokeh
    • css
    • HoloViews
    • Jupyter
    • Numpy
    • Pandas
    • PosgreSQL
    • Python 基本
    • python3
      • webアプリ
    • python3解説
    • scikit-learn
    • scipy
    • vps
    • Wordpress
    • グラフ
    • コマンド
    • スクレイピング
    • チートシート
    • データクレンジング
    • ブロックチェーン
    • 作成実績
    • 時系列分析
    • 機械学習
      • 分析手法
      • 教師有り
    • 異常値検知
    • 自然言語処理
  • 一太郎
  • 数学
    • sympy
      • 対数関数(log)
      • 累乗根(n乗根)
    • 暗号学

Copyright © 2025 · Genesis Sample on Genesis Framework · WordPress · Log in