ChatGPT: Use OpenAI to create your own AI website, and use the flask web framework to quickly build the main body of the website

Create your own AI website with OpenAI

If you are still a novice in OpenAI, have an OpenAI account, but want to call OpenAI API to do some interesting things, then this series of tutorials will explain in detail how to use OpenAI API to make your own AI website.

Use the flask web framework to quickly build the main body of the website

We have called the API interface of OpenAI before to request a "Little White Cat"

import openai

api_key = "sk-e4F4owy**********************"  # 此处是自己的API Key
openai.api_key = api_key

response = openai.Image.create(
  prompt = "a white siamese cat",
  n = 1,
  size = "1024x1024"
)
image_url = response['data'][0]['url']

print(image_url)

Today we will quickly build a simple web page, where we enter our request and ask OpenAI to provide us with a photo.

  1. To make our own AI website, we need to use the python web framework. Here we use the flask framework. The web frameworks commonly used in python are mainly flask and Django. As for the difference between the two frameworks, let ChatGPT tell you:

Hello, I would like to ask the difference between the flask framework and the Django framework, thank you!

The main differences between the Flask framework and the Django framework are as follows:

1. Flask is a lightweight framework, while Django is a heavyweight framework. Flask is essentially a micro-framework. The basic framework of the framework is very refined, suitable for rapid development of various simple projects, while Django is relatively complex in code and is generally used to develop various complex projects.

2. Flask can only be written in Python, while Django supports multiple programming languages ​​such as Python, Java, and JavaScript.

3. Flask is mainly used to develop APIs, Web services and personalized web pages, while Django is more suitable for building complex websites and applications, such as media sites, blogs, social networking sites, etc.

4. Flask does not implement ORM, and its templates are not very popular, while the Django framework has a mature ORM system and many popular template engines, making it very easy for users to deal with database queries and HTML template writing.

  1. As the old saying goes, first install the flask framework:
pip install flask
  1. After the installation is complete, let's try it out first. I believe that when you learn every language, the first sentence is to output a hello world. So today we also use the flask framework to output one on the web page: Life is short, I need python.
from flask import Flask

app = Flask(__name__)


@app.route('/')
def index():
    return 'Life is short, I need python.'


@app.route('/debug')
def debug():
    return 'I am Demo.'


if __name__ == '__main__':
    app.run(debug=True, port=8888)
  1. After running, you can see the URL in the console, click to enter:


  1. @app.route('/') The name of the route is in the brackets. We can access different content through different route names. For example, when we visit http://127.0.0.1:8888/, we get: Life is short, I need python. Visit http://127.0.0.1:8888/debug, what we get is I am Demo.

  1. It can be seen from the code that the actual return is the html code. We can copy the entire html to the return, but it is not friendly enough and inconvenient to debug. So we need to use another class of flask: render_template. How to use: render_template('index.html')
from flask import Flask, render_template

app = Flask(__name__)


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/debug')
def debug():
    return 'I am Demo.'


if __name__ == '__main__':
    app.run(debug=True, port=8888)
  1. We need to create a new templates folder in the project directory, and flask will automatically go to this folder to find the corresponding html file. Then we create a new index.html file in the templates folder and modify the content of the body: Demo's Html!
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    Demo's Html!
</body>
</html>



  1. Now we are going to manipulate the index.html file. First add a form to the interface, then add input boxes and buttons:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="">
        <input type="text" placeholder="请输入描述信息">
        <button>创作图画</button>
</form>
</body>
</html>
  1. In this way we get a very "beautiful" interface:

  1. After that, what we want to achieve is: after pressing the button, pass the text in the input box to the background. In this way, the background can submit the text we passed to OpenAI to request pictures.
  2. The Html file is as follows, what needs to be added is: 1. Form parameters: method="post" (here corresponds to the background processing method); 2. Add at input: name="desc" (desc will be passed to the background). That is: delivery method and delivery content.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/" method="post">
        <input type="text" name="desc" placeholder="请输入描述信息">
        <button>创作图画</button>

</form>
</body>
</html>
  1. The background code is as follows, add: methods=['GET', 'POST'] (for receiving and sending) and the code of the form receiving part
from flask import Flask, render_template, request

app = Flask(__name__)


@app.route('/', methods=['GET', 'POST'])
def index():
    # 此处我们应该接收html界面的文本
    if request.method == 'POST':  # 接收表单处理
        desc = request.form['desc']
        print(desc)

    return render_template('index.html')


@app.route('/debug')
def debug():
    return 'I am Demo.'


if __name__ == '__main__':
    app.run(debug=True, port=8888)
  1. Regarding the submission methods of GET and POST, it can be simply understood as: directly refreshing or accessing the page is GET; submitting to the background is POST.
  2. We can try to see if the content of the page is received in the console.

  1. Then we copy the OpenAI request part of the code to the location that receives the form processing.
from flask import Flask, render_template, request
import openai

api_key = "sk-e4F4owy**********************"  # 此处是自己的API Key
openai.api_key = api_key


app = Flask(__name__)


@app.route('/', methods=['GET', 'POST'])
def index():
    # 此处我们应该接收html界面的文本
    if request.method == 'POST':  # 接收表单处理
        desc = request.form['desc']
        print(desc)

        # 此处为OpenAI的API代码
        response = openai.Image.create(
            prompt=desc,
            n=1,
            size="1024x1024"
        )

        image_url = response['data'][0]['url']

        print(image_url)

    return render_template('index.html')


@app.route('/debug')
def debug():
    return 'I am Demo.'


if __name__ == '__main__':
    app.run(debug=True, port=8888)
  1. Enter the description you want OpenAI to create, and click Create Drawing. Check whether the information of the page is received in the background, and return a url.

  1. Let's take a look at what the earth looks like in 2050 in the mind of OpenAI.

  1. At this time, the picture is just a url, which needs to be opened by clicking the mouse from the background. How to display it on the page, we will talk about it in the next section, and it is to be continued. Please continue to pay attention~

Guess you like

Origin blog.csdn.net/ooowwq/article/details/130807484