如何将这个简单的CLI程序转换为在浏览器上运行?

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

我使用 Python 创建了一些简单的程序,这些程序基本上会询问用户问题以进行自省。它根据之前的答案一次提出一个问题。我希望用户能够登录并将他们的答案存储在数据库中。关于采取哪条路线有什么建议吗?您建议在网络上运行哪些语言和/或框架以供其他人使用?或者是否有任何现有的在线网站构建器网站可以允许此功能?

示例问题:

1. What is your goal? (user input)
2. Why do you want [response to question 1]? (user input)
3. Why do you want [response to question 2]? (user input)
4....
python html database
1个回答
0
投票

我用flask做了一个非常简单的程序来给你一些想法 (确保运行 pip install Flask)

创建一个名为app.py的文件:

from flask import Flask, render_template, request

# In-memory database (for simplicity)
questions = {
    1: "What is your goal?",
    2: "Why do you want [answer to question 1]?",
}
answers = {}  # Stores user answers

app = Flask(__name__)  # No need to specify template folder

max_question = max(questions.keys())

@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "POST":
        answer = request.form.get("answer")
        current_question = int(request.form.get("current_question"))
        answers[current_question] = answer
        next_question = current_question + 1
        if next_question > max_question:
            # Save answers to a text file
            save_answers()
            return "Thank you for your answers!"
        return render_template("questions.html", question=questions[next_question], current_question=next_question, max_question=max_question)
    return render_template("questions.html", question=questions[1], current_question=1, max_question=max_question)

def save_answers():
    with open("user_answers.txt", "w") as file:
        for question_id, answer in answers.items():
            file.write(f"Question {question_id}: {questions[question_id]}\n")
            file.write(f"Answer: {answer}\n")
            file.write("\n")

if __name__ == "__main__":
    app.run(debug=True)

现在,创建一个名为“templates”的文件夹。 在文件夹内,创建一个文件“questions.html” 并将其放入文件中

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Introspective Q&A</title>
</head>
<body>
    <h1>Introspection</h1>
    <form method="post">
        <p>{{ question }}</p>
        <label for="answer">Your answer:</label>
        <input type="text" name="answer" id="answer" required>
        <input type="hidden" name="current_question" value="{{ current_question }}">
        <br>
        <button type="submit">Next Question</button>
    </form>
    <br>
    {% if current_question == max_question %}
        <p>Thank you for your answers!</p>
    {% endif %}
</body>
</html>

应该是这样的

├── app.py
│   user_answers.txt
│
└──── templates/
    ─├── login.html
    ─└── questions.html

现在,在cmd“python app.py”中运行。这将为您创建一个网络服务器。从 cmd 复制地址并在网络浏览器中输入。

问题的答案将保存到user_answers.txt

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