使用Flask路由页面并在cPanel上部署

时间:2020-07-03 04:42:55

标签: python flask cpanel

嘿,我是不熟悉Flask并尝试建立我的第一个网站的人,现在已经尝试了几天,几乎没有进展,这是一些代码:

var request = require('request');
var mysql = require ('mysql');
var express = require ('express')
let config = require ('./config.js')
let connection = mysql.createConnection(config);
var app = express ();
var bodyParser = require('body-parser')
require('dotenv').config()

// start api operation from  db
var options = {
  'method': 'GET',
  'url': 'https://......,
  'headers': {
    'Cookie': ''
};
request(options, function(error, response) {
  if (error) throw new Error(error);
  console.log('getting the goods');
});
// end api operation

//start body-parser configuration
app.use(bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
}));
//end body-parser configuration

//create app server
var server = app.listen(3000,  "127.0.0.1", function () {

  var host = server.address().address
  var port = server.address().port

  console.log("i'm getting your data at http://%s:%s", host, port)

});
 // get data from customer api...
 var sql = `INSERT INTO dbname 
            (id, email, created_at, updated_at, first_name, last_name)
            VALUES ( '"+rec.body.id+"', '"+email+"', '"+created_at+"', '"+updated_at+"', '"+last_name+"', '"+first_name+"')`;
 var dbname = ['"id+"', '"+email+"', '"+created_at+"', '"+updated_at+"', '"+last_name+"', '"+first_name+"']

    console.log ("working")
   connection.query(sql, [dbname], (err, results, fields) => {
   if (err) {
  return console.error(err.message);
}
// get insrerted rows
   console.log('Row inserted:' + results.affectedRows);
});

 // close the database connection
  connection.end();
  console.log("disconnected")

第一个购买功能可以正常工作,当用户被重定向以继续时,会出现问题。 “ / confirm”标记已添加到网站的网址中,并且该网站转到“ 404未找到”页面。我在使用cPanel更改页面时遇到了问题。将网站用户发送到完全不同的页面的最佳方法是什么,我可以在其中添加自己选择的HTML文件。

2 个答案:

答案 0 :(得分:2)

首先,您需要将redirect(url_for('proceed'))更改为redirect(url_for('confirm'))

代码应如下所示:

from flask import Flask, render_template, url_for, redirect, request, session

app = Flask(__name__)

@app.route('/', methods=["POST", "GET"])
def purchase():
    try:
        
        if request.method == "POST":
            email = request.form["email"]
            # Query the data base to find the exact amount and name of buyer

            session["user"] = email
            return redirect(url_for("cofirm"))
            
        else:
            return render_template("index.html",logged_in=True)
            
    except Exception as e:
        return(str(e))


@app.route("/confirm")
def proceed():
    # Get information and create another form
    if "user" in session:
        return f"""<h1>{session["user"]}</h1>"""
    else:
        return f"""<h1>No email found</h1>"""
if __name__ == "__main__":
    
    app.run()

由于您是在Cpanel上托管,请更改.htaccess文件以添加以下内容,以便apache将所有未找到的URL重定向到您的应用程序

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . / [L]

答案 1 :(得分:2)

在应用程序URL目录中的.htaccess中添加以下规则

    public static void main(String[] args) throws IOException {

        FileWriter fw=new FileWriter("D:\\test.txt");
        fw.write("Hello! This is a sample text");
        System.out.println("Writing successful");
        fw.close();

        /* your code
        String path = "D:\\test1.txt";
        FileOutputStream fos = new FileOutputStream(path);
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos));
        out.write("Hello! This is a sample text");
        out.close(); 
        fos.close();
        */
    }