LoginSignup
2
5

More than 3 years have passed since last update.

【python】flaskを使ってローカルサーバーを動かしてみた

Posted at

はじめに

Progateでしかpythonを触ったことのない筆者が、pythonを使ってローカルサーバーを立てて、任意のアドレス対して動作をさせるまでの備忘録。

開発環境

Windows 10 64bit
Python 3.7.3
pip 19.3.1
flask 1.1.1

環境構築

pythonをインストールしていない人はまずはインストールをします!
詳しい方法はこちらから

インストールした記憶がないけどあるかも...と思う方はコマンドプロンプトを開いて、python -Vで確認してみましょう!

$ python --version
Python 3.7.3

$ python -V
Python 3.7.3

インストール済みであれば以上のように表示されます!

インストールが完了したら、Pythonのパッケージ管理ツールであるpipをインストールしていきます!
インストール済みか確認したい方は

python -m pip -V

で確認できます!
インストールされていなかった人は詳しいインストール方法はこちら

以下のコマンドを叩いてインストールしていきます!

py -m pip install pypdf2

インストールができたら、今回使うpythonの軽量フレームワークであるflaskのインストールを行っていきます!
flask使ったことのある人はこの記事を読まないであろうと想定して、インストールの仕方から!

pip install Flask

確認したいときは

$ python
>> import flask
>> flask.__version__

(\$マークはコピペしないでね。てかこの\$って何なんでしょう?)
ここまで出来たらとりあえずの環境構築は終了です。
おつかれさまでした。

さっそく実装

今回は前々回の記事で作成したreact-appでボタンをクリックしたときに指定したデータを返すような実装をしていきます。
前々回の記事→【React】はじめてReact触ってみた!~create-react-app編~
よかったらいいねしてください()

それはさておき、コードを書いていきます。
前回作ったもののフォルダとの相関関係はこんな感じです!

Sample
  └ resource
  └ react-test
      └ node_modules
      └ public
      └ src
          └ App.js
      ・
      ・
      ・
  └ flask-test
      └ run.py

まずは、いろいろなサイトを参考にpython側のコードを作成しました。

run.py
import json

# Flask などの必要なライブラリをインポートする
from flask import Flask
from flask_cors import CORS
from flask import request, make_response, jsonify

# 自身の名称を app という名前でインスタンス化する
app = Flask(__name__)
# CORS (Cross-Origin Resource Sharing)
CORS(app)

# ここからウェブアプリケーション用のルーティングを記述
# index にアクセスしたときの処理
@app.route('/', methods=['GET'])
def show_user():
    response = {'user': {'name': 'index', 'age': 'hoge', 'job': 'web'}}
    return make_response(jsonify(response))

# /user にアクセスしたときの処理
@app.route('/user', methods=['GET'])
def show_user2():
    response = {'user': {'name': 'user', 'age': 'fuga', 'job': 'free'}}
    return make_response(jsonify(response))


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

↓ 参考にした記事の数々はこちら ↓
ウェブアプリケーションフレームワーク Flask を使ってみる
PythonのFlaskを使用してWebアプリ作成してみよう(1)こんにちは世界
Flaskのユーザーガイド

続いて、以前create-react-appを使って作成したアプリを改造していきます!
react-test > App.js を開き、以下のようにした。

App.js
import React from 'react';
import logo from './logo.svg';
import './App.css';
import Axios from 'axios';

function App() {
  function click(){
    Axios.get('http://127.0.0.1:5000/').then(function(res){
      console.log(res);
      alert(res.data.user.age);
    }).catch(function(e){
      alert(e);
    })
  }

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React

          <br/>

        </a>
        <button onClick={() => {click()}}>click</button>

      </header>
    </div>
  );
}

export default App;

やっとこさ実行

ここまで来たらあとはコマンドプロンプトで動かすだけ!
早速コマンドプロンプトを開いて、

cd C:\Users\{user}\Documents\Sample\flask-test

で、指定ディレクトリに移動します。
ここで、

python run.py

を起動!

C:\Users\{user}\Documents\Sample\flask-test>python run.py
 * Serving Flask app "run" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

となれば成功!!

続いて、コマンドプロンプトを別ウィンドウでも開き、

cd C:\Users\{user}\Documents\Sample\react-test

でcreate-react-appのディレクトリに移動します。
そして前々回と同様に

C:\Users\{user}\Documents\Sample\react-test>npm start

で起動!これでうご...かない!?

Module not found: Can't resolve 'axios' ・・・

axiosのモジュールがないとか...
たしかに、インポートするaxiosのモジュールインストールした記憶ない...ってことで早速以下のコマンドを叩いてインストールします!

C:\Users\{user}\Documents\Sample\react-test>npm install axios

こんどこそいけるはず!ってことでもう一度

C:\Users\{user}\Documents\Sample\react-test>npm start

...

C:\Users\{user}\Documents\Sample\react-test>npm start
npm WARN lifecycle The node binary used for scripts is C:\Program Files (x86)\Nodist\bin\node.exe but npm is using C:\Program Files (x86)\Nodist\v-x64\10.15.3\node.exe itself. Use the `--scripts-prepend-node-path` option to include the path for the node binary npm was executed with.

> test@0.1.0 start C:\Users\sleep\Documents\React-Tutorial\test
> react-scripts start
Setting NODE_PATH to resolve modules absolutely has been deprecated in favor of setting baseUrl in jsconfig.json (or tsconfig.json if you are using TypeScript) and will be removed in a future major release of create-react-app.

Starting the development server...
Compiled successfully!

You can now view test in the browser.

  Local:            http://localhost:3000/
  On Your Network:  http://192.168.10.101:3000/

Note that the development build is not optimized.
To create a production build, use npm run build.

きた~~~~~~~~!

これでclickボタンを押すと...

hogeが返ってきた!!成功!!

次にclickしたときに飛ぶアドレスを変える!

App.js
function click(){
    Axios.get('http://127.0.0.1:5000/').then(function(res){
      console.log(res);
      alert(res.data.user.age);
    }).catch(function(e){
      alert(e);
    })
  }

これを

App.js
function click(){
    Axios.get('http://127.0.0.1:5000/user').then(function(res){
      console.log(res);
      alert(res.data.user.age);
    }).catch(function(e){
      alert(e);
    })
  }

こうして(アドレスの末尾にuserを追加)クリックボタンを押すと、

fugaに変わった!!!とりあえず想定通り動かせました、よかった~。
ちょっと躓くところもありましたが、環境構築さえできてしまえば何とかなりそうです!

おわりに

最後まで見てくださった方がいましたら、本当にありがとうございます。
初歩の初歩らしいところからやってみましたが、動かせるだけでめちゃくちゃうれしいものですね。
もっと改良してまたまとめていきたいと思います!

2
5
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
2
5