[Python] I tried running a local server using flask

Introduction

Until the author, who has only touched python with Progate, set up a local server using python and made it work for any address. memorandum.

Development environment

Windows 10 64bit Python 3.7.3 pip 19.3.1 flask 1.1.1

Environment

If you don't have python installed, install it first! For details, see here

If you don't remember installing it, but you think it might be ... open a command prompt and check with python -V!

$ python --version
Python 3.7.3

$ python -V
Python 3.7.3

If it is installed, it will be displayed as above!

Once the installation is complete, we will install the Python package management tool pip! If you want to check if it is installed

python -m pip -V

In can be confirmed! If you haven't installed it, please click here for detailed installation method (https://www.python-izm.com/tips/pip/)

Hit the following command to install!

py -m pip install pypdf2

Once installed, we will install flask, the lightweight framework for python used this time! Assuming that people who have used flask will not read this article, how to install it!

pip install Flask

When you want to check

$ python
>> import flask
>> flask.__version__

(Don't copy the \ $ mark. What is this \ $?) If you can do it so far, the environment construction is completed for the time being. Thank you for your support.

Implemented immediately

This time, we will implement it so that the specified data is returned when the button is clicked with the react-app created in the previous article. Article before last → [React] I tried React for the first time! ~ create-react-app edition ~ Please like if you like ()

Aside from that, I'll write the code. The correlation with the folder of the one I made last time is like this!

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

First of all, I created the code on the python side by referring to various sites.

run.py


import json

#Import the required libraries such as Flask
from flask import Flask
from flask_cors import CORS
from flask import request, make_response, jsonify

#Instantiate your name as app
app = Flask(__name__)
# CORS (Cross-Origin Resource Sharing)
CORS(app)

#Write the routing for your web application from here
#What happens when you access the index
@app.route('/', methods=['GET'])
def show_user():
    response = {'user': {'name': 'index', 'age': 'hoge', 'job': 'web'}}
    return make_response(jsonify(response))

# /What happens when you access 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()

↓ Click here for many articles that I referred to ↓ -Try using the web application framework Flask · Let's create Web app using the Python of Flask (1) Hello World](https://qiita.com/penpenta/items/47d23e2ea1decb4fb252) -Flask User Guide

Next, we will modify the app that was previously created using create-react-app! I opened react-test> App.js and did the following:

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;

Finally executed

Once you get here, all you have to do is run it at the command prompt! Immediately open a command prompt,

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

Moves to the specified directory. here,

python run.py

Start!

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)

If it becomes successful! !!

Then open the command prompt in a separate window

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

Go to the create-react-app directory with. And like the last time

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

Start with! This is moving ... no !?

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

There is no axios module ... Certainly, I don't remember installing the axios module to be imported ... So I immediately hit the following command to install it!

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

You should be able to go here! That ’s why again

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.

> [email protected] 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.

Kita ~~~~~~~~!

Now when you press the click button ...

hoge is back! !! success! !!

Change the flying address the next time you 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);
    })
  }

this

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);
    })
  }

When you press the click button (add user to the end of the address),

It changed to fuga! !! !! For the time being, I was able to move it as expected, which is good. There were some stumbling blocks, but once the environment was built, it would be quite so!

in conclusion

If anyone has seen it to the end, thank you very much. I tried it from a rudimentary place, but I'm really happy just to be able to move it. I would like to improve it further and summarize it again!

Recommended Posts

[Python] I tried running a local server using flask
I tried reading a CSV file using Python
I tried running alembic, a Python migration tool
[Python] I tried using OpenPose
Start a web server using Bottle and Flask (I also tried using Apache)
I tried running python etc. from a bat file
I tried drawing a pseudo fractal figure using Python
I tried using Python (3) instead of a scientific calculator
I made a Line-bot using Python!
I tried using Thonny (Python / IDE)
I tried Grumpy (Go running Python).
I tried running prolog with python 3.8.2.
[Python] I tried using YOLO v3
I tried to make a stopwatch using tkinter in python
I tried to make a regular expression of "amount" using Python
I tried playing a ○ ✕ game using TensorFlow
I tried to make a regular expression of "time" using Python
I tried drawing a line using turtle
I tried using Bayesian Optimization in Python
I tried to make a regular expression of "date" using Python
I tried using UnityCloudBuild API from Python
I tried to make a todo application using bottle with python
I made a poker game server chat-holdem using websocket with python
I tried using pipenv, so a memo
I made a Chatbot using LINE Messaging API and Python (2) ~ Server ~
I tried to communicate with a remote server by Socket communication with Python.
I tried to create a sample to access Salesforce using Python and Bottle
I want to make a web application using React and Python flask
vprof --I tried using the profiler for Python
I tried web scraping using python and selenium
[Python] Split a large Flask file using Blueprint
I tried object detection using Python and OpenCV
I tried playing a typing game in Python
I tried using mecab with python2.7, ruby2.3, php7
[Memo] I tried a pivot table in Python
I tried using Pythonect, a dataflow programming language.
I tried running faiss with python, Go, Rust
Launch a web server with Python and Flask
I tried using the Datetime module by Python
I tried running python -m summpy.server -h 127.0.0.1 -p 8080
I tried adding a Python3 module in C
I tried using firebase for Django's cache server
I tried running Deep Floor Plan with Python 3.6.10.
I tried using a database (sqlite3) with kivy
I tried to make a ○ ✕ game using TensorFlow
I made a Mattermost bot with Python (+ Flask)
I tried using argparse
I tried using anytree
I tried using aiomysql
I tried using Summpy
I tried using coturn
I tried using "Anvil".
I tried using Hubot
I tried using ESPCN
I tried using PyCaret
I tried using cron
I tried using ngrok
I tried using face_recognition
I tried using Jupyter
I tried using PyCaret
I tried using Heapq