如何将数据从React模板发送到Flask API?

问题描述 投票:-1回答:1

我想使用登录模板,但是我不确定如何将数据从该模板发送到我的Flask API。我读到状态仅在组件中。真的吗?我尝试从具有组件的另一个文件中的渲染器内部调用Register函数,但出现有关无效钩子的错误。

Flask API

from flask import Blueprint, jsonify
from flask import request, make_response
import sqlite3
from sqlite3 import Error
import os.path
import json

main = Blueprint('main', __name__)

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
db_path = os.path.join(BASE_DIR, "database.db")

def connection():
    try:
        conn = sqlite3.connect(db_path)
    except Error as e:
        print(e)
    return conn

@main.route('/add_review', methods=['POST'])
def add_review():
    conn = connection()
    cur = conn.cursor()

    req = request.get_json()
    busID = req.get('busID')
    userID = req.get('userID')
    review = req.get('review')
    rating = req.get('rating')

    sql = "INSERT INTO Review (businessID, userID, review, rating) VALUES (?, ?, ?, ?)"
    data = (busID, userID, review, rating)
    cur.execute(sql, data)

    conn.commit()
    cur.close()

    return 'Done', 201

@main.route('/reviews')
def reviews():
    conn = connection()
    cur = conn.cursor()
    name = "Halal Guys"
    cur.execute("SELECT * FROM Review where businessID = (SELECT id FROM Business where name = \'{}\')".format(name))
    reviews = cur.fetchall()

    reviews_dict = []
    for review in reviews:
        content = {"id": review[0], "busID": review[1], "userID": review[2],
                    "review": review[3], "rating": review[4]}
        reviews_dict.append(content)

    return json.dumps(reviews_dict)

@main.route('/createUser', methods=['POST', 'OPTIONS'])
def createUser():
    # handle option request
    if request.method == "OPTIONS":
        response = make_response()
        response.headers["Access-Control-Allow-Origin"] = "*"
        response.headers[
            "Access-Control-Allow-Headers"
        ] = "Origin, Accept, Content-Type"
        response.headers["Access-Control-Allow-Methods"] = "POST,OPTIONS"
        response.headers["Access-Control-Allow-Credentials"] = "true"
        return response

    if request.method == "POST":
        # do your SQL stuff
        conn = connection()
        cur = conn.cursor()

        req = request.get_json()
        first = req.get("FirstName")
        last = req.get("LastName")
        email = req.get("Email")
        pw = req.get("Password")

        sql = (
            "INSERT INTO User (first, last, emailAddress, password) VALUES (?, ?, ?, ?)"
        )
        data = (first, last, email, pw)
        cur.execute(sql, data)

        conn.commit()
        cur.close()

        # make response
        response = make_response("{}")  # return empty JSON response
        response.headers["Access-Control-Allow-Origin"] = "*"
        response.headers[
            "Content-Type"
        ] = "application/json"  # set response type to JSON
        return response

    return "", 405

登录模板

import React from 'react';
import Avatar from '@material-ui/core/Avatar';
import Button from '@material-ui/core/Button';
import CssBaseline from '@material-ui/core/CssBaseline';
import TextField from '@material-ui/core/TextField';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Checkbox from '@material-ui/core/Checkbox';
import Link from '@material-ui/core/Link';
import Grid from '@material-ui/core/Grid';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
import { makeStyles } from '@material-ui/core/styles';
import Container from '@material-ui/core/Container';

function Copyright() {
  return (
    <Typography variant="body2" color="textSecondary" align="center">
      {'Copyright © '}
      <Link color="inherit" href="https://material-ui.com/">
        Your Website
      </Link>{' '}
      {new Date().getFullYear()}
      {'.'}
    </Typography>
  );
}

const useStyles = makeStyles(theme => ({
  paper: {
    marginTop: theme.spacing(8),
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
  },
  avatar: {
    margin: theme.spacing(1),
    backgroundColor: theme.palette.secondary.main,
  },
  form: {
    width: '100%', // Fix IE 11 issue.
    marginTop: theme.spacing(3),
  },
  submit: {
    margin: theme.spacing(3, 0, 2),
  },
}));

export default function Register() {
  const classes = useStyles();

  return (
    <Container component="main" maxWidth="xs">
      <CssBaseline />
      <div className={classes.paper}>
        <Avatar className={classes.avatar}>
        </Avatar>
        <Typography component="h1" variant="h5">
          Sign up
        </Typography>
        <form className={classes.form} noValidate>
          <Grid container spacing={2}>
            <Grid item xs={12} sm={6}>
              <TextField
                autoComplete="fname"
                name="firstName"
                variant="outlined"
                required
                fullWidth
                id="firstName"
                label="First Name"
                autoFocus
              />
            </Grid>
            <Grid item xs={12} sm={6}>
              <TextField
                variant="outlined"
                required
                fullWidth
                id="lastName"
                label="Last Name"
                name="lastName"
                autoComplete="lname"
              />
            </Grid>
            <Grid item xs={12}>
              <TextField
                variant="outlined"
                required
                fullWidth
                id="email"
                label="Email Address"
                name="email"
                autoComplete="email"
              />
            </Grid>
            <Grid item xs={12}>
              <TextField
                variant="outlined"
                required
                fullWidth
                name="password"
                label="Password"
                type="password"
                id="password"
                autoComplete="current-password"
              />
            </Grid>
            <Grid item xs={12}>
              <FormControlLabel
                control={<Checkbox value="allowExtraEmails" color="primary" />}
                label="I want to receive inspiration, marketing promotions and updates via email."
              />
            </Grid>
          </Grid>
          <Button
            type="submit"
            fullWidth
            variant="contained"
            color="primary"
            className={classes.submit}
          >
            Sign Up
          </Button>
          <Grid container justify="flex-end">
            <Grid item>
              <Link href="/login" variant="body2">
                Already have an account? Sign in
              </Link>
            </Grid>
          </Grid>
        </form>
      </div>
      <Box mt={5}>
        <Copyright />
      </Box>
    </Container>
  );
}
javascript reactjs post flask flask-restful
1个回答
0
投票

尝试看一下react如何处理表格。 https://reactjs.org/docs/forms.html

© www.soinside.com 2019 - 2024. All rights reserved.