Hướng dẫn how can i run a python script from within flask? - làm cách nào để chạy tập lệnh python từ bên trong flask?

Tôi có một tập lệnh

$ python3 -m pip install 
9 tạo ra một trang web và in một số dữ liệu một cách linh hoạt. - Dữ liệu mà nó in nên đến từ một tập lệnh Python khác.

Show

Vấn đề hiện tại mà tôi đang gặp phải là nếu tôi đặt dòng thực thi tập lệnh Python trước dòng thực thi ứng dụng

$ python3 -m pip install 
9, nó sẽ chạy tập lệnh Python mà không cần chạy
$ python3 -m pip install 
9; và ngược lại.

Kịch bản Python:

import websocket
from bitmex_websocket import Instrument
from bitmex_websocket.constants import InstrumentChannels
from bitmex_websocket.constants import Channels
import json

websocket.enableTrace(True)

sells = 0
buys = 0


channels = [
    InstrumentChannels.trade,
]


XBTUSD = Instrument(symbol='XBTUSD',
                    channels=channels)
XBTUSD.on('action', lambda msg: test(msg))


def test(msg):
    parsed = json.loads(json.dumps(msg))


    print(parsed)

XBTUSD.run_forever()

Tập lệnh Flask (NB: Giá phải là biến 'được phân tích cú pháp' từ tập lệnh khác):

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)

Bạn đã viết một kịch bản Python mà bạn tự hào, và bây giờ bạn muốn thể hiện nó với thế giới. Nhưng bằng cách nào? Hầu hết mọi người đã giành chiến thắng biết phải làm gì với tệp

app-engine-python 1.9.91
bq 2.0.62
cloud-datastore-emulator 2.1.0
core 2020.11.13
gsutil 4.55
2 của bạn. Chuyển đổi tập lệnh của bạn thành ứng dụng web Python là một giải pháp tuyệt vời để làm cho mã của bạn có thể sử dụng được cho đối tượng rộng.Python web application is a great solution to make your code usable for a broad audience.

Trong khóa học này, bạn sẽ học cách chuyển từ tập lệnh Python địa phương đến một ứng dụng web được triển khai đầy đủ mà bạn có thể chia sẻ với thế giới.

Đến cuối khóa học này, bạn sẽ biết:

  • Ứng dụng web là gì và làm thế nào bạn có thể lưu trữ chúng trực tuyếnweb applications are and how you can host them online
  • Cách chuyển đổi tập lệnh Python thành ứng dụng Web FlaskFlask web application
  • Cách cải thiện trải nghiệm người dùng bằng cách thêm HTML vào mã Python của bạnadding HTML to your Python code
  • Cách triển khai ứng dụng web Python của bạn cho Công cụ ứng dụng Googledeploy your Python web application to Google App Engine

Xem bây giờ hướng dẫn này có một khóa học video liên quan được tạo bởi nhóm Python thực sự. Xem nó cùng với hướng dẫn bằng văn bản để hiểu sâu hơn về sự hiểu biết của bạn: Triển khai tập lệnh Python của bạn trên web bằng bình This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Deploy Your Python Script on the Web With Flask

Bạn đã viết một kịch bản Python mà bạn tự hào, và bây giờ bạn muốn thể hiện nó với thế giới. Nhưng bằng cách nào? Hầu hết mọi người đã giành chiến thắng biết phải làm gì với tệp

app-engine-python 1.9.91
bq 2.0.62
cloud-datastore-emulator 2.1.0
core 2020.11.13
gsutil 4.55
2 của bạn. Chuyển đổi tập lệnh của bạn thành ứng dụng web Python là một giải pháp tuyệt vời để làm cho mã của bạn có thể sử dụng được cho đối tượng rộng.Python web application is a great solution to make your code usable for a broad audience.

Trong hướng dẫn này, bạn sẽ học cách đi từ kịch bản Python địa phương đến một ứng dụng web được triển khai đầy đủ mà bạn có thể chia sẻ với thế giới.

Đến cuối hướng dẫn này, bạn sẽ biết:

  • Ứng dụng web là gì và làm thế nào bạn có thể lưu trữ chúng trực tuyếnweb applications are and how you can host them online
  • Cách chuyển đổi tập lệnh Python thành ứng dụng Web FlaskFlask web application
  • Cách cải thiện trải nghiệm người dùng bằng cách thêm HTML vào mã Python của bạnadding HTML to your Python code
  • Cách triển khai ứng dụng web Python của bạn cho Công cụ ứng dụng Googledeploy your Python web application to Google App Engine

Ngoài việc đi bộ qua một dự án ví dụ, bạn sẽ tìm thấy một số bài tập trong suốt hướng dẫn. Họ sẽ cho bạn một cơ hội để củng cố những gì bạn đang học thông qua thực hành thêm. Bạn cũng có thể tải xuống mã nguồn mà bạn sẽ sử dụng để xây dựng ứng dụng web của mình bằng cách nhấp vào liên kết bên dưới:exercises throughout the tutorial. They’ll give you a chance to solidify what you’re learning through extra practice. You can also download the source code that you’ll use to build your web application by clicking the link below:

Chải lên những điều cơ bản

Trong phần này, bạn sẽ nhận được một bước chân lý thuyết trong các chủ đề khác nhau mà bạn sẽ làm việc trong phần thực tế của hướng dẫn này:

  • Những loại phân phối mã python tồn tại
  • Tại sao xây dựng một ứng dụng web có thể là một lựa chọn tốt
  • Ứng dụng Web là gì
  • Làm thế nào nội dung được phân phối qua internet
  • Lưu trữ web có nghĩa là gì
  • Nhà cung cấp lưu trữ nào tồn tại và sử dụng cái nào

Trải lên các chủ đề này có thể giúp bạn cảm thấy tự tin hơn khi viết mã Python cho web. Tuy nhiên, nếu bạn đã quen thuộc với họ, thì hãy bỏ qua phía trước, hãy cài đặt Google Cloud SDK và bắt đầu xây dựng ứng dụng web Python của bạn.

Phân phối mã Python của bạn

Mang mã của bạn cho người dùng của bạn được gọi là phân phối. Theo truyền thống, có ba cách tiếp cận khác nhau mà bạn có thể sử dụng để phân phối mã của mình để những người khác có thể làm việc với các chương trình của bạn:distribution. Traditionally, there are three different approaches you can use to distribute your code so that others can work with your programs:

  1. Thư viện Python
  2. Chương trình độc lập
  3. Ứng dụng web Python

Bạn sẽ xem xét kỹ hơn về từng cách tiếp cận dưới đây.

Thư viện Python

Nếu bạn đã làm việc với hệ sinh thái gói rộng rãi của Python, thì bạn có thể đã cài đặt các gói Python với

app-engine-python 1.9.91
bq 2.0.62
cloud-datastore-emulator 2.1.0
core 2020.11.13
gsutil 4.55
4. Là một lập trình viên, bạn có thể muốn xuất bản gói Python của mình trên PYPI để cho phép người dùng khác truy cập và sử dụng mã của bạn bằng cách cài đặt nó bằng cách sử dụng
app-engine-python 1.9.91
bq 2.0.62
cloud-datastore-emulator 2.1.0
core 2020.11.13
gsutil 4.55
4:

$ python3 -m pip install 

Sau khi bạn đã xuất bản thành công mã của mình lên PYPI, lệnh này sẽ cài đặt gói của bạn, bao gồm cả các phụ thuộc của nó, trên bất kỳ máy tính người dùng nào của bạn, với điều kiện họ có kết nối Internet.

Nếu bạn không muốn xuất bản mã của mình dưới dạng gói PYPI, thì bạn vẫn có thể sử dụng lệnh Python, tích hợp

app-engine-python 1.9.91
bq 2.0.62
cloud-datastore-emulator 2.1.0
core 2020.11.13
gsutil 4.55
6 để tạo phân phối nguồn hoặc bánh xe Python để tạo phân phối được xây dựng để chia sẻ với người dùng của bạn.

Phân phối mã của bạn như thế này giữ cho nó gần với kịch bản gốc mà bạn đã viết và chỉ thêm những gì cần thiết cho người khác để chạy nó. Tuy nhiên, sử dụng phương pháp này cũng có nghĩa là người dùng của bạn sẽ cần chạy mã của bạn với Python. Nhiều người muốn sử dụng tập lệnh của bạn chức năng của bạn, won đã được cài đặt Python hoặc giành được quen thuộc với các quy trình cần thiết để làm việc trực tiếp với mã của bạn.

Một cách thân thiện hơn với người dùng để trình bày mã của bạn cho người dùng tiềm năng là xây dựng một chương trình độc lập.

Chương trình độc lập

Các chương trình máy tính có các hình dạng và hình thức khác nhau, và có nhiều tùy chọn để chuyển đổi tập lệnh Python của bạn thành các chương trình độc lập. Dưới đây bạn sẽ đọc về hai khả năng:

  1. Bao bì mã của bạn
  2. Xây dựng GUI

Các chương trình như PyInstaller, PY2App, PY2EXE hoặc cặp có thể giúp đóng gói mã của bạn. Họ biến các tập lệnh Python thành các chương trình thực thi có thể được sử dụng trên các nền tảng khác nhau mà không yêu cầu người dùng của bạn chạy rõ ràng trình thông dịch Python.

Mặc dù đóng gói mã của bạn có thể giải quyết các vấn đề phụ thuộc, mã của bạn vẫn chỉ chạy trên dòng lệnh. Hầu hết mọi người đều quen làm việc với các chương trình cung cấp giao diện người dùng đồ họa (GUI). Bạn có thể làm cho mã Python của bạn có thể truy cập được cho nhiều người hơn bằng cách xây dựng GUI cho nó.

Mặc dù chương trình máy tính để bàn GUI độc lập có thể giúp mã của bạn có thể truy cập được với đối tượng rộng hơn, nhưng nó vẫn gây trở ngại cho mọi người để bắt đầu. Trước khi chạy chương trình của bạn, người dùng tiềm năng có một vài bước để vượt qua. Họ cần tìm phiên bản phù hợp cho hệ điều hành của họ, tải xuống và cài đặt thành công nó. Một số có thể từ bỏ trước khi họ làm cho nó tất cả các cách.

Thay vào đó, nhiều nhà phát triển xây dựng các ứng dụng web có thể được truy cập nhanh chóng và chạy trên trình duyệt internet.

Ứng dụng web Python

Ưu điểm của các ứng dụng web là nền tảng của họ độc lập và có thể được điều hành bởi bất kỳ ai có quyền truy cập vào Internet. Mã của chúng được triển khai trên máy chủ back-end, trong đó chương trình xử lý các yêu cầu đến và trả lời thông qua một giao thức được chia sẻ mà Lọ hiểu bởi tất cả các trình duyệt.server, where the program processes incoming requests and responds through a shared protocol that’s understood by all browsers.

Python cung cấp năng lượng cho nhiều ứng dụng web lớn và là một lựa chọn phổ biến như một ngôn ngữ back-end. Nhiều ứng dụng web điều khiển Python được lên kế hoạch bắt đầu như các ứng dụng web và được xây dựng bằng các khung web Python như Flask, mà bạn sẽ sử dụng trong hướng dẫn này.

Tuy nhiên, thay vì cách tiếp cận đầu tiên được mô tả ở trên, bạn sẽ có một góc độ khác. Rốt cuộc, bạn có kế hoạch xây dựng một ứng dụng web. Bạn vừa tạo ra một kịch bản Python hữu ích, và bây giờ bạn muốn chia sẻ với thế giới. Để làm cho nó có thể truy cập được nhiều người dùng, bạn sẽ tái cấu trúc nó thành một ứng dụng web và sau đó triển khai nó vào Internet.

Đó là thời gian để xem xét một ứng dụng web là như thế nào và nó khác với nội dung khác trên web.

Tìm hiểu về các ứng dụng web Python

Trong lịch sử, các trang web có nội dung cố định giống nhau cho mọi người dùng truy cập trang đó. Các trang web này được gọi là tĩnh vì nội dung của chúng không thay đổi khi bạn tương tác với chúng. Khi phục vụ một trang web tĩnh, một máy chủ web trả lời yêu cầu của bạn bằng cách gửi lại nội dung của trang đó, bất kể bạn là ai hoặc những hành động khác bạn đã thực hiện.static because their content doesn’t change when you interact with them. When serving a static web page, a web server responds to your request by sending back the content of that page, regardless of who you are or what other actions you took.

Bạn có thể duyệt một ví dụ về một trang web tĩnh ở URL đầu tiên từng lên mạng, cũng như các trang mà nó liên kết đến:

Hướng dẫn how can i run a python script from within flask? - làm cách nào để chạy tập lệnh python từ bên trong flask?
Lịch sử của www

Các trang web tĩnh như vậy aren đã xem xét các ứng dụng vì nội dung của chúng được tạo ra một cách động bởi mã. Mặc dù các trang web tĩnh được sử dụng để tạo ra tất cả các internet, hầu hết các trang web ngày nay là các ứng dụng web thực sự, cung cấp các trang web động có thể thay đổi nội dung mà chúng cung cấp.web applications, which offer dynamic web pages that can change the content they deliver.

Chẳng hạn, một ứng dụng webmail cho phép bạn tương tác với nó theo nhiều cách. Tùy thuộc vào hành động của bạn, nó có thể hiển thị các loại thông tin khác nhau, thường là ở trong một trang duy nhất:

Hướng dẫn how can i run a python script from within flask? - làm cách nào để chạy tập lệnh python từ bên trong flask?
Một ứng dụng webmail một trang

Các ứng dụng web dựa trên Python sử dụng mã Python để xác định những hành động nào sẽ thực hiện và nội dung nào để hiển thị. Mã của bạn được chạy bởi máy chủ web lưu trữ trang web của bạn, điều đó có nghĩa là người dùng của bạn không cần phải cài đặt bất cứ thứ gì. Tất cả những gì họ cần để tương tác với mã của bạn là trình duyệt và kết nối internet. use Python code to determine what actions to take and what content to show. Your code is run by the web server that hosts your website, which means that your users don’t need to install anything. All they need to interact with your code is a browser and an Internet connection.

Bắt Python chạy trên một trang web có thể phức tạp, nhưng có một số khung web khác nhau tự động chăm sóc các chi tiết. Như đã đề cập ở trên, bạn sẽ xây dựng một ứng dụng bình cơ bản trong hướng dẫn này.

Trong phần sắp tới, bạn sẽ nhận được một viễn cảnh cấp cao về các quy trình chính cần phải chạy mã Python của bạn trên máy chủ và cung cấp phản hồi cho người dùng của bạn.

Xem lại chu kỳ phản hồi yêu cầu HTTP

Phục vụ nội dung động trên Internet liên quan đến rất nhiều phần khác nhau và tất cả chúng phải liên lạc với nhau để hoạt động chính xác. Tại đây, một tổng quan tổng quát về những gì diễn ra khi người dùng tương tác với ứng dụng web:

  1. Gửi: Đầu tiên, người dùng của bạn đưa ra yêu cầu cho một trang web cụ thể trên ứng dụng web của bạn. Họ có thể làm điều này, ví dụ, bằng cách nhập URL vào trình duyệt của họ. First, your user makes a request for a particular web page on your web app. They can do this, for example, by typing a URL into their browser.

  2. Nhận: Yêu cầu này được nhận bởi máy chủ web lưu trữ trang web của bạn. This request gets received by the web server that hosts your website.

  3. Phù hợp: Máy chủ web của bạn hiện sử dụng một chương trình để phù hợp với yêu cầu của người dùng với một phần cụ thể của tập lệnh Python của bạn. Your web server now uses a program to match the user’s request to a particular portion of your Python script.

  4. Chạy: Mã Python thích hợp được chương trình đó gọi lên. Khi mã của bạn chạy, nó viết ra một trang web dưới dạng phản hồi. The appropriate Python code is called up by that program. When your code runs, it writes out a web page as a response.

  5. Cung cấp: Chương trình sau đó cung cấp phản hồi này cho người dùng của bạn thông qua máy chủ web. The program then delivers this response back to your user through the web server.

  6. Xem: Cuối cùng, người dùng có thể xem phản hồi của máy chủ web. Ví dụ: trang web kết quả có thể được hiển thị trong trình duyệt. Finally, the user can view the web server’s response. For example, the resulting web page can be displayed in a browser.

Đây là một quá trình chung về cách phân phối nội dung qua Internet. Ngôn ngữ lập trình được sử dụng trên máy chủ, cũng như các công nghệ được sử dụng để thiết lập kết nối đó, có thể khác nhau. Tuy nhiên, khái niệm được sử dụng để liên lạc qua các yêu cầu và phản hồi HTTP vẫn giữ nguyên và được gọi là chu kỳ phản hồi yêu cầu HTTP.requests and responses remains the same and is called the HTTP Request-Response Cycle.

Để cho phép Flask xử lý các yêu cầu ở phía máy chủ, bạn sẽ cần tìm một nơi mà mã Python của bạn có thể sống trực tuyến. Lưu trữ mã trực tuyến của bạn để chạy một ứng dụng web được gọi là lưu trữ web và có một số nhà cung cấp cung cấp cả lưu trữ web được trả tiền và miễn phí.web hosting, and there are a number of providers offering both paid and free web hosting.

Chọn nhà cung cấp dịch vụ lưu trữ: Công cụ ứng dụng Google

Khi chọn nhà cung cấp dịch vụ lưu trữ web, bạn cần xác nhận rằng nó hỗ trợ chạy mã Python. Nhiều người trong số họ tốn tiền, nhưng hướng dẫn này sẽ gắn bó với một tùy chọn miễn phí mà chuyên nghiệp và có khả năng mở rộng cao nhưng vẫn hợp lý để thiết lập: Google App Engine.

Có một số tùy chọn miễn phí khác, chẳng hạn như Pythonanywhere, Repress.it hoặc Heroku mà bạn có thể khám phá sau này. Sử dụng Google App Engine sẽ cho bạn một khởi đầu tốt trong việc tìm hiểu về việc triển khai mã Python lên web khi nó đạt được sự cân bằng giữa việc trừu tượng hóa sự phức tạp và cho phép bạn tùy chỉnh thiết lập.

Google App Engine là một phần của nền tảng Google Cloud (GCP), được điều hành bởi Google và đại diện cho một trong những nhà cung cấp đám mây lớn, cùng với Microsoft Azure và Amazon Web Services (AWS).

Để bắt đầu với GCP, hãy tải xuống và cài đặt Google Cloud SDK cho hệ điều hành của bạn. Để được hướng dẫn bổ sung ngoài những gì bạn sẽ tìm thấy trong hướng dẫn này, bạn có thể tham khảo tài liệu của Google App Engine.

Cài đặt Google Cloud SDK cũng bao gồm một chương trình dòng lệnh có tên

app-engine-python 1.9.91
bq 2.0.62
cloud-datastore-emulator 2.1.0
core 2020.11.13
gsutil 4.55
7, mà sau đó bạn sẽ sử dụng để triển khai ứng dụng web của mình. Khi bạn đã hoàn thành việc cài đặt, bạn có thể xác minh rằng mọi thứ đã hoạt động bằng cách nhập lệnh sau vào bảng điều khiển của bạn:

Bạn sẽ nhận được một đầu ra văn bản trong thiết bị đầu cuối của bạn trông giống như dưới đây:

app-engine-python 1.9.91
bq 2.0.62
cloud-datastore-emulator 2.1.0
core 2020.11.13
gsutil 4.55

Số phiên bản của bạn có thể sẽ khác nhau, nhưng miễn là chương trình

app-engine-python 1.9.91
bq 2.0.62
cloud-datastore-emulator 2.1.0
core 2020.11.13
gsutil 4.55
7 được tìm thấy thành công trên máy tính của bạn, việc cài đặt của bạn đã thành công.

Với tổng quan cấp cao này về các khái niệm và SDK Google Cloud được cài đặt, bạn đã sẵn sàng thiết lập một dự án Python mà sau đó bạn sẽ triển khai lên Internet.

Xây dựng một ứng dụng web Python cơ bản

Công cụ ứng dụng Google yêu cầu bạn sử dụng khung web để tạo ứng dụng web của mình trong môi trường Python 3. Vì bạn đang cố gắng sử dụng một thiết lập tối thiểu để đưa mã python cục bộ của bạn lên internet, một bộ vi tính như Flask là một lựa chọn tốt. Một triển khai tối thiểu của bình nhỏ đến mức bạn thậm chí có thể không nhận thấy rằng bạn đang sử dụng khung web.

Ứng dụng mà bạn sẽ tạo sẽ dựa vào một số tệp khác nhau, vì vậy điều đầu tiên bạn cần làm là tạo một thư mục dự án để giữ tất cả các tệp này.

Thiết lập dự án của bạn

Tạo một thư mục dự án và đặt cho nó một cái tên mô tả về dự án của bạn. Đối với dự án thực hành này, hãy gọi thư mục

app-engine-python 1.9.91
bq 2.0.62
cloud-datastore-emulator 2.1.0
core 2020.11.13
gsutil 4.55
9. Bạn sẽ cần ba tệp bên trong thư mục này:

  1.  1from flask import Flask
     2
     3app = Flask(__name__)
     4
     5@app.route("/")
     6def index():
     7    return "Congratulations, it's a web app!"
    
    0 chứa mã Python của bạn được bọc trong việc triển khai tối thiểu khung web của Flask.
    contains your Python code wrapped in a minimal implementation of the Flask web framework.
  2.  1from flask import Flask
     2
     3app = Flask(__name__)
     4
     5@app.route("/")
     6def index():
     7    return "Congratulations, it's a web app!"
    
    1 liệt kê tất cả các phụ thuộc mã của bạn cần phải hoạt động đúng.
    lists all the dependencies your code needs to work properly.
  3.  1from flask import Flask
     2
     3app = Flask(__name__)
     4
     5@app.route("/")
     6def index():
     7    return "Congratulations, it's a web app!"
    
    2 giúp Google App Engine quyết định cài đặt nào sẽ sử dụng trên máy chủ của mình.
    helps Google App Engine decide which settings to use on its server.

Mặc dù ba tệp có thể nghe rất nhiều, nhưng bạn sẽ thấy rằng dự án này sử dụng ít hơn mười dòng mã trên cả ba tệp. Điều này thể hiện thiết lập tối thiểu bạn cần cung cấp cho Google App Engine cho bất kỳ dự án Python nào bạn có thể khởi chạy. Phần còn lại sẽ là mã Python của riêng bạn. Bạn có thể tải xuống mã nguồn đầy đủ mà bạn sẽ sử dụng trong hướng dẫn này bằng cách nhấp vào liên kết bên dưới:

Tiếp theo, bạn sẽ xem nội dung của từng tệp bắt đầu với tệp phức tạp nhất,

 1from flask import Flask
 2
 3app = Flask(__name__)
 4
 5@app.route("/")
 6def index():
 7    return "Congratulations, it's a web app!"
0.

Tạo 1from flask import Flask 2 3app = Flask(__name__) 4 [email protected]("/") 6def index(): 7 return "Congratulations, it's a web app!" 0

 1from flask import Flask
 2
 3app = Flask(__name__)
 4
 5@app.route("/")
 6def index():
 7    return "Congratulations, it's a web app!"
0 là tệp mà Flask sử dụng để cung cấp nội dung của bạn. Ở đầu tệp, bạn nhập lớp
$ python3 -m pip install 
9 trên dòng 1, sau đó bạn tạo một thể hiện của một ứng dụng bình trên dòng 3:

 1from flask import Flask
 2
 3app = Flask(__name__)
 4
 5@app.route("/")
 6def index():
 7    return "Congratulations, it's a web app!"

Sau khi bạn tạo bình

 1from flask import Flask
 2
 3app = Flask(__name__)
 4
 5@app.route("/")
 6def index():
 7    return "Congratulations, it's a web app!"
7, bạn viết một trình trang trí python trên dòng 5 có tên
 1from flask import Flask
 2
 3app = Flask(__name__)
 4
 5@app.route("/")
 6def index():
 7    return "Congratulations, it's a web app!"
8 mà Flask sử dụng để kết nối các điểm cuối URL với mã có trong các chức năng. Đối số của
 1from flask import Flask
 2
 3app = Flask(__name__)
 4
 5@app.route("/")
 6def index():
 7    return "Congratulations, it's a web app!"
8 xác định thành phần đường dẫn URL, đó là đường dẫn gốc (
$ source venv/bin/activate
0) trong trường hợp này.

Mã trên các dòng 6 và 7 tạo nên

$ source venv/bin/activate
1, được bao bọc bởi người trang trí. Hàm này xác định những gì nên được thực thi nếu điểm cuối URL được xác định được yêu cầu bởi người dùng. Giá trị trả về của nó xác định những gì người dùng sẽ thấy khi họ tải trang.

Nói cách khác, nếu người dùng nhập URL cơ sở của ứng dụng web của bạn vào trình duyệt của họ, thì Flask chạy

$ source venv/bin/activate
1 và người dùng thấy văn bản được trả về. Trong trường hợp này, văn bản đó chỉ là một câu:
$ source venv/bin/activate
3

Bạn có thể hiển thị nội dung phức tạp hơn và bạn cũng có thể tạo nhiều hơn một chức năng để người dùng có thể truy cập các điểm cuối URL khác nhau trong ứng dụng của bạn để nhận các phản hồi khác nhau. Tuy nhiên, đối với việc triển khai ban đầu này, nó rất tốt khi gắn bó với thông điệp thành công ngắn và đáng khích lệ này.

Tạo 1from flask import Flask 2 3app = Flask(__name__) 4 [email protected]("/") 6def index(): 7 return "Congratulations, it's a web app!" 1

Tệp tiếp theo để xem là

 1from flask import Flask
 2
 3app = Flask(__name__)
 4
 5@app.route("/")
 6def index():
 7    return "Congratulations, it's a web app!"
1. Vì Flask là sự phụ thuộc duy nhất của dự án này, nên tất cả những gì bạn cần chỉ định:

Nếu ứng dụng của bạn có các phụ thuộc khác, thì bạn cũng sẽ cần thêm chúng vào tệp

 1from flask import Flask
 2
 3app = Flask(__name__)
 4
 5@app.route("/")
 6def index():
 7    return "Congratulations, it's a web app!"
1 của mình.

Công cụ ứng dụng Google sẽ sử dụng

 1from flask import Flask
 2
 3app = Flask(__name__)
 4
 5@app.route("/")
 6def index():
 7    return "Congratulations, it's a web app!"
1 để cài đặt các phụ thuộc Python cần thiết cho dự án của bạn khi thiết lập nó trên máy chủ. Điều này tương tự như những gì bạn sẽ làm sau khi tạo và kích hoạt một môi trường ảo mới tại địa phương.

Tạo 1from flask import Flask 2 3app = Flask(__name__) 4 [email protected]("/") 6def index(): 7 return "Congratulations, it's a web app!" 2

Tệp thứ ba,

 1from flask import Flask
 2
 3app = Flask(__name__)
 4
 5@app.route("/")
 6def index():
 7    return "Congratulations, it's a web app!"
2, giúp Google App Engine thiết lập đúng môi trường máy chủ cho mã của bạn. Tệp này chỉ yêu cầu một dòng, xác định thời gian chạy Python:

Dòng hiển thị ở trên làm rõ rằng thời gian chạy phù hợp cho mã Python của bạn là Python 3.8. Điều này là đủ để Công cụ ứng dụng Google thực hiện thiết lập cần thiết trên các máy chủ của mình.

Bạn có thể sử dụng tệp Google App Engine, ____ ____ ____42 để thiết lập bổ sung, chẳng hạn như thêm các biến môi trường vào ứng dụng của bạn. Bạn cũng có thể sử dụng nó để xác định đường dẫn đến nội dung tĩnh cho ứng dụng của mình, chẳng hạn như hình ảnh, CSS hoặc tệp JavaScript. Hướng dẫn này đã giành được các cài đặt bổ sung này, nhưng bạn có thể tham khảo tài liệu của Google App Engine trên tệp cấu hình

 1from flask import Flask
 2
 3app = Flask(__name__)
 4
 5@app.route("/")
 6def index():
 7    return "Congratulations, it's a web app!"
2 nếu bạn muốn thêm chức năng đó.

Chín dòng mã này hoàn thành thiết lập cần thiết cho ứng dụng này. Dự án của bạn hiện đã sẵn sàng để triển khai.

Tuy nhiên, đó là cách thực hành tốt để kiểm tra mã của bạn trước khi đưa nó vào sản xuất để bạn có thể nắm bắt các lỗi tiềm năng. Tiếp theo, bạn sẽ kiểm tra xem mọi thứ có hoạt động như mong đợi tại địa phương trước khi triển khai mã của bạn lên Internet hay không.

Kiểm tra cục bộ

Flask được đóng gói với một máy chủ web phát triển. Bạn có thể sử dụng máy chủ phát triển này để kiểm tra kỹ mã mà mã của bạn hoạt động như mong đợi. Để có thể chạy máy chủ phát triển Flask tại địa phương, bạn cần hoàn thành hai bước. Công cụ ứng dụng Google sẽ thực hiện các bước tương tự trên máy chủ của mình sau khi bạn triển khai mã của mình:

  1. Thiết lập một môi trường ảo.
  2. Cài đặt gói
    $ python3 -m pip install -r requirements.txt
    
    2.

Để thiết lập môi trường ảo Python 3, hãy điều hướng đến thư mục dự án của bạn trên thiết bị đầu cuối của bạn và nhập lệnh sau:

Điều này sẽ tạo ra một môi trường ảo mới có tên

$ python3 -m pip install -r requirements.txt
3 bằng phiên bản Python 3 mà bạn đã cài đặt trên hệ thống của mình. Tiếp theo, bạn cần kích hoạt môi trường ảo bằng cách tìm kiếm tập lệnh kích hoạt:

$ source venv/bin/activate

Sau khi thực hiện lệnh này, lời nhắc của bạn sẽ thay đổi để cho biết rằng bạn hiện đang hoạt động từ trong môi trường ảo. Sau khi bạn thiết lập thành công và kích hoạt môi trường ảo của mình, bạn đã sẵn sàng cài đặt bình:

$ python3 -m pip install -r requirements.txt

Lệnh này lấy tất cả các gói được liệt kê trong

 1from flask import Flask
 2
 3app = Flask(__name__)
 4
 5@app.route("/")
 6def index():
 7    return "Congratulations, it's a web app!"
1 từ PYPI và cài đặt chúng trong môi trường ảo của bạn. Trong trường hợp này, gói duy nhất được cài đặt sẽ là bình.

Chờ cài đặt hoàn tất, sau đó mở

 1from flask import Flask
 2
 3app = Flask(__name__)
 4
 5@app.route("/")
 6def index():
 7    return "Congratulations, it's a web app!"
0 và thêm hai dòng mã sau ở dưới cùng của tệp:

if __name__ == "__main__":
    app.run(host="127.0.0.1", port=8080, debug=True)

Hai dòng này bảo Python khởi động máy chủ phát triển Flask Flask khi tập lệnh được thực thi từ dòng lệnh. Nó chỉ được sử dụng khi bạn chạy tập lệnh cục bộ. Khi bạn triển khai mã cho Google App Engine, một quy trình máy chủ web chuyên nghiệp, chẳng hạn như Gunicorn, sẽ phục vụ ứng dụng thay thế. Bạn đã thắng cần phải thay đổi bất cứ điều gì để thực hiện điều này.

Bây giờ bạn có thể khởi động máy chủ phát triển Flask Flask và tương tác với ứng dụng Python của bạn trong trình duyệt của bạn. Để làm như vậy, bạn cần chạy tập lệnh Python khởi động ứng dụng bình bằng cách nhập lệnh sau:

Bình khởi động máy chủ phát triển và thiết bị đầu cuối của bạn sẽ hiển thị đầu ra tương tự như văn bản được hiển thị bên dưới:

 * Serving Flask app "main" (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: on
 * Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 315-059-987

Đầu ra này cho bạn biết ba phần thông tin quan trọng:

  1. $ python3 -m pip install -r requirements.txt
    
    6: Đây là máy chủ phát triển Flask Flask, có nghĩa là bạn không muốn sử dụng nó để phục vụ mã của mình trong sản xuất. Thay vào đó, Google App Engine sẽ xử lý điều đó cho bạn. This is Flask’s development server, which means you don’t want to use it to serve your code in production. Google App Engine will handle that for you instead.

  2. $ python3 -m pip install -r requirements.txt
    
    7: Đây là URL nơi bạn có thể tìm thấy ứng dụng của mình. Nó có URL cho Localhost của bạn, điều đó có nghĩa là ứng dụng đang chạy trên máy tính của riêng bạn. Điều hướng đến URL đó trong trình duyệt của bạn để xem mã của bạn trực tiếp. This is the URL where you can find your app. It’s the URL for your localhost, which means the app is running on your own computer. Navigate to that URL in your browser to see your code live.

  3. $ python3 -m pip install -r requirements.txt
    
    8: cùng một dòng cũng cho bạn biết rằng bạn có thể thoát khỏi máy chủ phát triển bằng cách nhấn Ctrl+C trên bàn phím của mình. The same line also tells you that you can exit the development server by pressing Ctrl+C on your keyboard.

Thực hiện theo các hướng dẫn và mở tab Trình duyệt tại

$ python3 -m pip install -r requirements.txt
9. Bạn sẽ thấy một trang hiển thị văn bản mà chức năng của bạn trả về:
$ source venv/bin/activate
3

Bạn có thể sử dụng máy chủ phát triển Flask Flask để kiểm tra mọi thay đổi mà bạn thực hiện đối với mã của ứng dụng Python của bạn. Máy chủ lắng nghe các thay đổi bạn thực hiện trong mã và sẽ tự động tải lại để hiển thị chúng. Nếu ứng dụng của bạn không kết xuất như bạn mong đợi trên máy chủ phát triển, thì nó cũng đã giành được công việc trong sản xuất. Vì vậy, hãy chắc chắn rằng nó có vẻ tốt trước khi bạn triển khai nó.

Ngoài ra, hãy nhớ rằng ngay cả khi nó hoạt động tốt tại địa phương, nó có thể không hoạt động hoàn toàn giống nhau khi được triển khai. Điều này là do có các yếu tố khác liên quan khi bạn triển khai mã của mình lên Công cụ ứng dụng Google. Tuy nhiên, đối với một ứng dụng cơ bản như ứng dụng mà bạn xây dựng trong hướng dẫn này, bạn có thể tự tin rằng nó sẽ hoạt động trong sản xuất nếu nó hoạt động tốt tại địa phương.

Thay đổi giá trị trả về của

$ source venv/bin/activate
1 và xác nhận rằng bạn có thể thấy sự thay đổi được phản ánh trong trình duyệt của bạn. Chơi xung quanh với nó. Điều gì xảy ra khi bạn thay đổi giá trị trả về của mã
$ source venv/bin/activate
1 thành mã HTML, chẳng hạn như
if __name__ == "__main__":
    app.run(host="127.0.0.1", port=8080, debug=True)
3, thay vì sử dụng chuỗi văn bản đơn giản?

Sau khi kiểm tra thiết lập của bạn và chức năng mã mã trên máy chủ phát triển cục bộ của bạn, bạn đã chuẩn bị triển khai nó với Google App Engine.

Triển khai ứng dụng web Python của bạn

Cuối cùng, thời gian để đưa ứng dụng của bạn lên mạng. Nhưng trước tiên, mã của bạn cần một nơi để sống trên các máy chủ của Google và bạn cần đảm bảo rằng nó sẽ đến đó an toàn. Trong phần này của hướng dẫn, bạn sẽ làm việc để hoàn thành các thiết lập triển khai cần thiết cả trong đám mây và địa phương.

Thiết lập trên công cụ ứng dụng Google

Đọc qua quá trình thiết lập dưới đây từng bước. Bạn có thể so sánh những gì bạn thấy trong trình duyệt của bạn với ảnh chụp màn hình. Tên dự án được sử dụng trong ảnh chụp màn hình ví dụ là

app-engine-python 1.9.91
bq 2.0.62
cloud-datastore-emulator 2.1.0
core 2020.11.13
gsutil 4.55
9.

Bắt đầu bằng cách đăng nhập vào nền tảng Google Cloud. Điều hướng đến chế độ xem bảng điều khiển, nơi bạn sẽ thấy một thanh công cụ ở đầu cửa sổ. Chọn nút mũi tên hướng xuống về phía bên trái của thanh công cụ. Điều này sẽ xuất hiện một phương thức chứa danh sách các dự án Google của bạn:

Hướng dẫn how can i run a python script from within flask? - làm cách nào để chạy tập lệnh python từ bên trong flask?

Phương thức hiển thị một danh sách các dự án của bạn. Danh sách này có thể trống nếu bạn đã tạo ra bất kỳ dự án nào. Ở phía trên bên phải của phương thức đó, hãy tìm nút dự án mới và nhấp vào nó:

Hướng dẫn how can i run a python script from within flask? - làm cách nào để chạy tập lệnh python từ bên trong flask?

Nhấp vào dự án mới sẽ chuyển hướng bạn đến một trang mới, nơi bạn có thể quyết định tên cho dự án của mình. Tên này sẽ xuất hiện trong URL của ứng dụng của bạn, sẽ trông tương tự như

if __name__ == "__main__":
    app.run(host="127.0.0.1", port=8080, debug=True)
5. Sử dụng
app-engine-python 1.9.91
bq 2.0.62
cloud-datastore-emulator 2.1.0
core 2020.11.13
gsutil 4.55
9 làm tên cho dự án này để phù hợp với hướng dẫn:

Hướng dẫn how can i run a python script from within flask? - làm cách nào để chạy tập lệnh python từ bên trong flask?

Bạn có thể thấy ID dự án của bạn bên dưới trường đầu vào tên dự án. ID dự án bao gồm tên bạn đã nhập và một số mà Google App Engine bổ sung. Trong trường hợp của hướng dẫn này, bạn có thể thấy rằng ID dự án là

if __name__ == "__main__":
    app.run(host="127.0.0.1", port=8080, debug=True)
7. Sao chép ID dự án cá nhân của bạn vì bạn sẽ cần nó sau này để triển khai.

Bây giờ bạn có thể nhấp vào Tạo và chờ dự án được thiết lập ở phía Google App Engine. Khi đã hoàn thành, một thông báo sẽ xuất hiện cho bạn biết rằng một dự án mới đã được tạo ra. Nó cũng cung cấp cho bạn tùy chọn để chọn nó. Hãy tiếp tục và làm điều đó bằng cách nhấp vào Chọn Dự án:

Hướng dẫn how can i run a python script from within flask? - làm cách nào để chạy tập lệnh python từ bên trong flask?

Nhấp vào Chọn Dự án sẽ chuyển hướng bạn đến trang chính của dự án nền tảng Google Cloud mới của bạn. Có vẻ như thế này:

Hướng dẫn how can i run a python script from within flask? - làm cách nào để chạy tập lệnh python từ bên trong flask?

Từ đây, bạn muốn chuyển sang bảng điều khiển của Google App Engine. Bạn có thể làm điều đó bằng cách nhấp vào menu hamburger ở trên cùng bên trái, cuộn xuống để chọn Công cụ ứng dụng trong danh sách đầu tiên, sau đó chọn bảng điều khiển trên đầu danh sách bật lên tiếp theo:

Hướng dẫn how can i run a python script from within flask? - làm cách nào để chạy tập lệnh python từ bên trong flask?

Điều này cuối cùng sẽ chuyển hướng bạn đến chế độ xem bảng điều khiển động cơ Google App về dự án mới của bạn. Vì dự án trống cho đến nay, trang này sẽ trông giống như thế này:

Hướng dẫn how can i run a python script from within flask? - làm cách nào để chạy tập lệnh python từ bên trong flask?

Khi bạn thấy trang này, điều đó có nghĩa là bạn đã hoàn thành việc thiết lập một dự án mới trên Google App Engine. Bây giờ bạn đã sẵn sàng quay trở lại thiết bị đầu cuối trên máy tính của bạn và hoàn thành các bước cục bộ cần thiết để triển khai ứng dụng của bạn cho dự án này.

Thiết lập địa phương để triển khai

Sau khi cài đặt thành công Google Cloud SDK, bạn có quyền truy cập vào giao diện dòng lệnh

app-engine-python 1.9.91
bq 2.0.62
cloud-datastore-emulator 2.1.0
core 2020.11.13
gsutil 4.55
7. Chương trình này đi kèm với các hướng dẫn hữu ích hướng dẫn bạn thông qua việc triển khai ứng dụng web của bạn. Bắt đầu bằng cách nhập lệnh được đề xuất cho bạn khi bạn tạo một dự án mới trên trang web của Google App Engine:

Hướng dẫn how can i run a python script from within flask? - làm cách nào để chạy tập lệnh python từ bên trong flask?

Như bạn có thể thấy ở góc dưới bên phải của trang, Google App Engine đề xuất lệnh đầu cuối để triển khai mã của bạn cho dự án này. Mở thiết bị đầu cuối của bạn, điều hướng đến thư mục dự án của bạn, sau đó chạy lệnh được đề xuất:

Khi bạn thực hiện lệnh này mà không cần thiết lập trước đó, chương trình sẽ trả lời bằng thông báo lỗi:

ERROR: (gcloud.app.deploy)
You do not currently have an active account selected.
Please run:

  $ gcloud auth login

to obtain new credentials.

If you have already logged in with a different account:

    $ gcloud config set account ACCOUNT

to select an already authenticated account to use.

Bạn nhận được thông báo lỗi này vì bạn có thể triển khai bất kỳ mã nào vào tài khoản công cụ Google ứng dụng của mình trừ khi bạn chứng minh với Google rằng bạn là chủ sở hữu của tài khoản đó. Bạn cần phải xác thực với tài khoản Google App Engine từ máy tính cục bộ của bạn.

Ứng dụng dòng lệnh

app-engine-python 1.9.91
bq 2.0.62
cloud-datastore-emulator 2.1.0
core 2020.11.13
gsutil 4.55
7 đã cung cấp cho bạn lệnh mà bạn cần chạy. Nhập nó vào thiết bị đầu cuối của bạn:

Điều này sẽ bắt đầu quá trình xác thực bằng cách tạo URL xác thực và mở nó trong trình duyệt của bạn. Hoàn thành quy trình bằng cách chọn tài khoản Google của bạn trong cửa sổ trình duyệt và cấp cho Google Cloud SDK các đặc quyền cần thiết. Sau khi bạn làm điều này, bạn có thể quay lại thiết bị đầu cuối của mình, nơi bạn sẽ thấy một số thông tin về quy trình xác thực:

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
0

Nếu bạn thấy tin nhắn này, thì xác thực đã thành công. Bạn cũng có thể thấy rằng chương trình dòng lệnh một lần nữa cung cấp cho bạn thông tin hữu ích về bước tiếp theo của bạn.

Nó cho bạn biết rằng hiện tại không có bộ dự án nào và bạn có thể đặt một bộ bằng cách chạy

 * Serving Flask app "main" (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: on
 * Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 315-059-987
0. Bây giờ bạn sẽ cần ID dự án mà bạn đã lưu ý trước đó.

Hãy chắc chắn thay thế

if __name__ == "__main__":
    app.run(host="127.0.0.1", port=8080, debug=True)
7 bằng ID dự án của riêng bạn khi chạy lệnh được đề xuất:

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
1

Thiết bị đầu cuối của bạn sẽ in ra một thông báo phản hồi ngắn mà tài sản dự án đã được cập nhật. Sau khi xác thực thành công và đặt dự án mặc định cho ID dự án của bạn, bạn đã hoàn thành các bước thiết lập cần thiết.

Chạy quá trình triển khai

Bây giờ bạn đã sẵn sàng để thử lệnh triển khai ban đầu lần thứ hai:

Ứng dụng

app-engine-python 1.9.91
bq 2.0.62
cloud-datastore-emulator 2.1.0
core 2020.11.13
gsutil 4.55
7 tìm hiểu thông tin xác thực của bạn cũng như thông tin ID dự án từ cấu hình mặc định mà bạn vừa thiết lập và cho phép bạn tiến hành. Tiếp theo, bạn cần chọn một khu vực mà ứng dụng của bạn sẽ được lưu trữ:

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
2

Nhập một trong các số được liệt kê ở phía bên trái và nhấn Enter.Enter.

Sau khi bạn nhập một số, CLI sẽ tiếp tục với quy trình thiết lập. Trước khi triển khai mã của bạn lên Công cụ ứng dụng Google, nó sẽ cho bạn thấy tổng quan về việc triển khai sẽ trông như thế nào và yêu cầu bạn xác nhận cuối cùng:

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
3

Sau khi bạn xác nhận thiết lập bằng cách gõ y, việc triển khai của bạn cuối cùng sẽ trên đường đi. Thiết bị đầu cuối của bạn sẽ hiển thị cho bạn thêm một số thông tin và một hoạt hình tải nhỏ trong khi Google App Engine thiết lập dự án của bạn trên máy chủ của nó:Y, your deployment will finally be on its way. Your terminal will show you some more information and a small loading animation while Google App Engine sets up your project on its servers:

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
4

Vì đây là lần triển khai đầu tiên của ứng dụng web của bạn, nên có thể mất vài phút để hoàn thành. Sau khi triển khai kết thúc, bạn sẽ thấy một đầu ra hữu ích khác trong bảng điều khiển. Nó trông giống như cái dưới đây:

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
5

Bây giờ bạn có thể điều hướng đến URL đã đề cập trong trình duyệt của mình hoặc nhập lệnh được đề xuất

 * Serving Flask app "main" (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: on
 * Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 315-059-987
3 để truy cập ứng dụng web trực tiếp của bạn. Bạn sẽ thấy phản hồi văn bản ngắn giống như bạn đã thấy trước đó khi chạy ứng dụng trên localhost của bạn:
$ source venv/bin/activate
3

Lưu ý rằng trang web này có một URL mà bạn có thể chia sẻ với người khác và họ sẽ có thể truy cập nó. Bây giờ bạn có một ứng dụng web Python trực tiếp!

Thay đổi giá trị trả về của

$ source venv/bin/activate
1 một lần nữa và triển khai ứng dụng của bạn lần thứ hai bằng lệnh
 * Serving Flask app "main" (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: on
 * Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 315-059-987
6. Xác nhận rằng bạn có thể thấy sự thay đổi được phản ánh trên trang web trực tiếp trong trình duyệt của bạn.

Với điều này, bạn đã hoàn thành các bước cần thiết để đưa mã Python cục bộ của mình lên web. Tuy nhiên, chức năng duy nhất mà bạn đã đặt trực tuyến cho đến nay là in ra một chuỗi văn bản.

Thời gian để đẩy nó lên! Theo quy trình tương tự, bạn sẽ mang lại chức năng thú vị hơn trực tuyến trong phần tiếp theo. Bạn sẽ tái cấu trúc mã của tập lệnh chuyển đổi nhiệt độ cục bộ thành một ứng dụng web Flask.

Chuyển đổi tập lệnh thành ứng dụng web

Vì hướng dẫn này là về việc tạo và triển khai các ứng dụng web Python từ mã bạn đã có, mã Python cho tập lệnh chuyển đổi nhiệt độ được cung cấp cho bạn tại đây:

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
6

Đây là một kịch bản ngắn cho phép người dùng chuyển đổi nhiệt độ Celsius thành nhiệt độ Fahrenheit tương đương.

Lưu mã dưới dạng tập lệnh Python và cung cấp cho nó một vòng quay. Hãy chắc chắn rằng nó hoạt động như mong đợi và bạn hiểu những gì nó làm. Hãy thoải mái cải thiện mã.

Với tập lệnh hoạt động này trong tay, bây giờ bạn sẽ cần thay đổi mã để tích hợp nó vào ứng dụng bình của bạn. Có hai điểm chính cần xem xét để làm điều đó:

  • Thực thi: Làm thế nào ứng dụng web sẽ biết khi nào nên chạy mã? How will the web app know when to run the code?
  • Đầu vào của người dùng: ứng dụng web sẽ thu thập đầu vào của người dùng như thế nào? How will the web app collect user input?

Bạn đã học cách nói với Flask để thực thi một đoạn mã cụ thể bằng cách thêm mã vào một hàm mà bạn chỉ định một tuyến đường. Bắt đầu bằng cách giải quyết nhiệm vụ này đầu tiên.

Thêm mã làm hàm

Bình phân tách các nhiệm vụ khác nhau thành các chức năng khác nhau được chỉ định một tuyến đường thông qua trình trang trí

 1from flask import Flask
 2
 3app = Flask(__name__)
 4
 5@app.route("/")
 6def index():
 7    return "Congratulations, it's a web app!"
8. Khi người dùng truy cập tuyến đường được chỉ định thông qua URL của nó, mã bên trong hàm tương ứng sẽ được thực thi.

Bắt đầu bằng cách thêm

 * Serving Flask app "main" (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: on
 * Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 315-059-987
8 vào tệp
 1from flask import Flask
 2
 3app = Flask(__name__)
 4
 5@app.route("/")
 6def index():
 7    return "Congratulations, it's a web app!"
0 của bạn và gói nó với trình trang trí
 1from flask import Flask
 2
 3app = Flask(__name__)
 4
 5@app.route("/")
 6def index():
 7    return "Congratulations, it's a web app!"
8:

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
7

Cho đến nay, bạn chỉ sao chép mã tập lệnh Python của mình vào một chức năng trong ứng dụng bình của bạn và thêm trình trang trí

 1from flask import Flask
 2
 3app = Flask(__name__)
 4
 5@app.route("/")
 6def index():
 7    return "Congratulations, it's a web app!"
8.

Tuy nhiên, đã có một vấn đề với thiết lập này. Điều gì xảy ra khi bạn chạy mã trong máy chủ phát triển của bạn? Hãy thử một lần.

Hiện tại, cả hai chức năng của bạn đều được kích hoạt bởi cùng một tuyến (

$ source venv/bin/activate
0). Khi người dùng truy cập tuyến đó, bình chọn hàm đầu tiên phù hợp với nó và thực thi mã đó. Trong trường hợp của bạn, điều này có nghĩa là
 * Serving Flask app "main" (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: on
 * Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 315-059-987
8 không bao giờ được thực thi vì
$ source venv/bin/activate
1 khớp với cùng một tuyến và được gọi là đầu tiên.

Chức năng thứ hai của bạn sẽ cần con đường độc đáo của riêng mình để có thể truy cập được. Ngoài ra, bạn vẫn cần cho phép người dùng của bạn cung cấp đầu vào cho chức năng của bạn.

Truyền các giá trị cho mã của bạn

Bạn có thể giải quyết cả hai tác vụ này bằng cách nói với bình xử lý bất kỳ phần nào còn lại của URL theo URL cơ sở dưới dạng giá trị và chuyển nó cho chức năng của bạn. Điều này chỉ đòi hỏi một thay đổi nhỏ đối với tham số của trình trang trí

 1from flask import Flask
 2
 3app = Flask(__name__)
 4
 5@app.route("/")
 6def index():
 7    return "Congratulations, it's a web app!"
8 trước
 * Serving Flask app "main" (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: on
 * Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 315-059-987
8:

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
8

Cú pháp khung góc (

ERROR: (gcloud.app.deploy)
You do not currently have an active account selected.
Please run:

  $ gcloud auth login

to obtain new credentials.

If you have already logged in with a different account:

    $ gcloud config set account ACCOUNT

to select an already authenticated account to use.
7) bảo cho bình giữ bất kỳ văn bản nào theo URL cơ sở (
$ source venv/bin/activate
0) và chuyển nó cho chức năng mà bộ trang trí kết thúc dưới dạng biến
ERROR: (gcloud.app.deploy)
You do not currently have an active account selected.
Please run:

  $ gcloud auth login

to obtain new credentials.

If you have already logged in with a different account:

    $ gcloud config set account ACCOUNT

to select an already authenticated account to use.
9. Lưu ý rằng
 * Serving Flask app "main" (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: on
 * Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 315-059-987
8 yêu cầu
ERROR: (gcloud.app.deploy)
You do not currently have an active account selected.
Please run:

  $ gcloud auth login

to obtain new credentials.

If you have already logged in with a different account:

    $ gcloud config set account ACCOUNT

to select an already authenticated account to use.
9 làm đầu vào.

Quay trở lại trình duyệt web của bạn và thử chức năng mới bằng máy chủ phát triển Flask Flask. Bây giờ bạn có thể truy cập cả hai chức năng của mình thông qua ứng dụng web của mình bằng các điểm cuối URL khác nhau:

  • INDEX (
    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    02): Nếu bạn truy cập URL cơ sở, thì bạn sẽ thấy thông điệp đáng khích lệ từ trước.
    If you go to the base URL, then you’ll see the short encouraging message from before.
  • Celsius (
    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    03): Nếu bạn thêm một số sau khi chém về phía trước, thì bạn sẽ thấy nhiệt độ được chuyển đổi xuất hiện trong trình duyệt của bạn.
    If you add a number after the forward slash, then you’ll see the converted temperature appear in your browser.

Chơi xung quanh với nó thêm một số và thử nhập các đầu vào khác nhau. Ngay cả việc xử lý lỗi từ tập lệnh của bạn vẫn hoạt động và hiển thị thông báo khi người dùng nhập vào đầu vào không phải là người. Ứng dụng web của bạn xử lý chức năng tương tự như tập lệnh Python của bạn đã làm cục bộ, chỉ bây giờ bạn mới có thể triển khai nó lên Internet.

Tái cấu trúc mã của bạn

Flask là một khung web trưởng thành cho phép bạn giao rất nhiều nhiệm vụ cho nội bộ của nó. Ví dụ: bạn có thể để Flask chăm sóc loại kiểm tra đầu vào cho chức năng của mình và trả về thông báo lỗi nếu nó không phù hợp. Tất cả điều này có thể được thực hiện với một cú pháp ngắn gọn bên trong tham số thành

 1from flask import Flask
 2
 3app = Flask(__name__)
 4
 5@app.route("/")
 6def index():
 7    return "Congratulations, it's a web app!"
8. Thêm phần sau vào người bị bắt đường dẫn của bạn:type checking the input to your function and returning an error message if it doesn’t fit. All this can be done with a concise syntax inside of the parameter to
 1from flask import Flask
 2
 3app = Flask(__name__)
 4
 5@app.route("/")
 6def index():
 7    return "Congratulations, it's a web app!"
8. Add the following to your path capturer:

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
9

Thêm

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
05 trước khi tên biến cho Bình kiểm tra xem đầu vào có nhận được từ URL có thể được chuyển đổi thành số nguyên hay không. Nếu nó có thể, thì nội dung được chuyển sang
 * Serving Flask app "main" (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: on
 * Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 315-059-987
8. Nếu nó có thể, thì Flask sẽ hiển thị trang lỗi
# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
07.

Sau khi áp dụng kiểm tra loại Flask Flask, giờ đây bạn có thể loại bỏ khối

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
08 ____10109 trong
 * Serving Flask app "main" (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: on
 * Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 315-059-987
8. Chỉ các số nguyên mới từng được truyền vào chức năng bằng bình:

$ python3 -m pip install 
0

Với điều này, bạn đã hoàn thành việc chuyển đổi tập lệnh chuyển đổi nhiệt độ của mình thành một ứng dụng web. Xác nhận rằng mọi thứ hoạt động như mong đợi tại địa phương, sau đó triển khai ứng dụng của bạn một lần nữa với Google App Engine.

Tái cấu trúc

$ source venv/bin/activate
1. Nó sẽ trả về văn bản giải thích cách sử dụng ứng dụng web chuyển đổi nhiệt độ. Hãy nhớ rằng bạn có thể sử dụng thẻ HTML trong chuỗi trả về. HTML sẽ hiển thị đúng trên trang đích của bạn.

Sau khi triển khai thành công ứng dụng web chuyển đổi nhiệt độ của bạn sang Internet, giờ đây bạn có một liên kết mà bạn có thể chia sẻ với người khác và cho phép họ chuyển đổi nhiệt độ Celsius sang nhiệt độ Fahrenheit.

Tuy nhiên, giao diện vẫn trông khá cơ bản và ứng dụng web hoạt động giống API hơn là ứng dụng web Front-end. Nhiều người dùng có thể không biết cách tương tác với ứng dụng web Python của bạn ở trạng thái hiện tại. Điều này cho bạn thấy những hạn chế của việc sử dụng Python thuần túy để phát triển web.

Nếu bạn muốn tạo các giao diện trực quan hơn, thì bạn sẽ cần bắt đầu sử dụng ít nhất một chút HTML.

Trong phần tiếp theo, bạn sẽ tiếp tục lặp lại mã của mình và sử dụng HTML để tạo một hộp đầu vào cho phép người dùng nhập một số trực tiếp trên trang thay vì thông qua URL.input box that allows users to enter a number directly on the page rather than through the URL.

Cải thiện giao diện người dùng của ứng dụng web của bạn

Trong phần này, bạn sẽ học cách thêm phần tử nhập HTML

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
12 vào ứng dụng web của bạn để cho phép người dùng tương tác với nó một cách đơn giản mà họ đã sử dụng từ các ứng dụng trực tuyến khác.

Để cải thiện giao diện người dùng và trải nghiệm người dùng ứng dụng web của bạn, bạn sẽ cần phải làm việc với các ngôn ngữ khác ngoài Python, cụ thể là các ngôn ngữ phía trước như HTML, CSS và JavaScript. Hướng dẫn này tránh đi vào những điều này càng nhiều càng tốt, để duy trì tập trung vào việc sử dụng Python.

Tuy nhiên, nếu bạn muốn thêm một hộp đầu vào vào ứng dụng web của mình, thì bạn sẽ cần sử dụng một số HTML. Bạn chỉ triển khai mức tối thiểu tuyệt đối để có được ứng dụng web của bạn trông và cảm thấy giống như một trang web mà người dùng sẽ quen thuộc. Bạn sẽ sử dụng phần tử HTML

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
12 để thu thập đầu vào của họ.

Sau khi cập nhật ứng dụng web của bạn, bạn sẽ có một trường văn bản nơi người dùng có thể nhập nhiệt độ tính theo độ C. Sẽ có một nút chuyển đổi để chuyển đổi nhiệt độ Celsius do người dùng cung cấp thành độ Fahrenheit:

Kết quả đã chuyển đổi sẽ được hiển thị trên dòng tiếp theo và sẽ được cập nhật bất cứ khi nào người dùng nhấp vào Chuyển đổi.

Bạn cũng sẽ thay đổi chức năng của ứng dụng để cả biểu mẫu và kết quả chuyển đổi được hiển thị trên cùng một trang. Bạn sẽ tái cấu trúc mã để bạn chỉ cần một điểm cuối URL.

Thu thập đầu vào của người dùng

Bắt đầu bằng cách tạo phần tử

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
12 trên trang đích của bạn. Sao chép một vài dòng HTML sau vào câu lệnh trả về của
$ source venv/bin/activate
1, thay thế tin nhắn văn bản từ trước:

$ python3 -m pip install 
1

Khi bạn tải lại trang của mình tại URL cơ sở, bạn sẽ thấy một hộp đầu vào và một nút. HTML hiển thị chính xác. Xin chúc mừng, bạn vừa tạo một biểu mẫu đầu vào!

Điều gì xảy ra khi bạn nhập giá trị và sau đó nhấp vào Chuyển đổi? Mặc dù trang trông giống nhau, bạn có thể nhận thấy rằng URL đã thay đổi. Bây giờ nó hiển thị một tham số truy vấn có giá trị sau URL cơ sở.query parameter with a value after the base URL.

Ví dụ: nếu bạn đã nhập

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
16 vào hộp văn bản và nhấp vào nút, thì URL của bạn sẽ trông như thế này:
# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
17. Đây là tin tốt! Giá trị đã được ghi lại thành công và được thêm vào dưới dạng tham số truy vấn vào yêu cầu HTTP nhận được. Nhìn thấy URL này có nghĩa là bạn một lần nữa yêu cầu URL cơ sở, nhưng lần này với một số giá trị bổ sung mà bạn đã gửi cùng.

Tuy nhiên, không có gì hiện tại xảy ra với giá trị bổ sung đó. Mặc dù biểu mẫu được thiết lập như vậy, nhưng nó chưa được kết nối chính xác với chức năng mã của ứng dụng web Python của bạn.

Để hiểu cách tạo kết nối đó, bạn sẽ đọc về từng phần của phần tử

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
12 để xem tất cả các phần khác nhau là gì. Bạn sẽ xem xét ba yếu tố sau và các thuộc tính của chúng một cách riêng biệt:

  1. Phần tử
    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    12
  2. Hộp đầu vào
  3. Gửi nút

Mỗi trong số này là các yếu tố HTML riêng biệt. Mặc dù hướng dẫn này nhằm mục đích tập trung vào Python chứ không phải HTML, nhưng nó vẫn hữu ích để có một sự hiểu biết cơ bản về những gì diễn ra trong khối mã HTML này. Bắt đầu bằng cách nhìn vào phần tử HTML ngoài cùng.

Phần tử
# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
12

Phần tử

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
12 tạo biểu mẫu HTML. Hai yếu tố
# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
22 còn lại được bọc bên trong nó:

$ python3 -m pip install 
2

Phần tử

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
12 cũng chứa hai thuộc tính HTML được gọi là
# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
24 và
# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
25:HTML attributes called
# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
24 and
# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
25:

  • # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    24 xác định nơi dữ liệu mà người dùng sẽ gửi. Bạn có thể để lại giá trị như một chuỗi trống ở đây, điều này làm cho trình duyệt của bạn hướng yêu cầu đến cùng một URL mà nó được gọi từ. Trong trường hợp của bạn, đó là URL cơ sở trống. determines where the data that the user submits will be sent. You’re leaving the value as an empty string here, which makes your browser direct the request to the same URL it was called from. In your case, that’s the empty base URL.

  • # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    25 Xác định loại HTTP yêu cầu biểu mẫu tạo ra. Sử dụng mặc định là
    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    28 tạo ra yêu cầu Get HTTP. Điều này có nghĩa là dữ liệu do người dùng gửi sẽ được hiển thị trong các tham số truy vấn URL. Nếu bạn đã gửi dữ liệu nhạy cảm hoặc liên lạc với cơ sở dữ liệu, thì bạn sẽ cần sử dụng yêu cầu bài HTTP thay thế.
    defines what type of HTTP request the form produces. Using the default of
    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    28 creates an HTTP GET request. This means that the user-submitted data will be visible in the URL query parameters. If you were submitting sensitive data or communicating with a database, then you would need to use an HTTP POST request instead.

Sau khi kiểm tra phần tử

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
12 và các thuộc tính của nó, bước tiếp theo của bạn là xem xét kỹ hơn về phần đầu tiên của hai phần tử
# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
22.

Hộp đầu vào

Phần tử HTML thứ hai là một phần tử

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
22 mà lồng nhau bên trong phần tử
# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
12:

$ python3 -m pip install 
3

Phần tử

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
22 đầu tiên có hai thuộc tính HTML:

  1. # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    34 Xác định loại phần tử
    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    22 nên được tạo. Có rất nhiều lựa chọn, chẳng hạn như hộp kiểm và các yếu tố thả xuống. Trong trường hợp này, bạn muốn người dùng nhập một số dưới dạng văn bản, vì vậy bạn đã đặt loại thành
    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    36.
    defines what type of
    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    22 element should be created. There are many to choose from, such as checkboxes and drop-down elements. In this case, you want the user to enter a number as text, so you’re setting the type to
    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    36.

  2. # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    37 Xác định giá trị mà người dùng nhập sẽ được gọi là gì. Bạn có thể nghĩ về nó như là chìa khóa cho một từ điển, trong đó giá trị là bất cứ điều gì người dùng nhập vào hộp văn bản. Bạn thấy tên này hiển thị trong URL là khóa của tham số truy vấn. Bạn sẽ cần khóa này sau này để lấy lại giá trị do người dùng gửi. defines what the value the user enters will be referred to as. You can think of it as the key to a dictionary, where the value is whatever the user inputs into the text box. You saw this name show up in the URL as the key of the query parameter. You’ll need this key later to retrieve the user-submitted value.

Các yếu tố HTML

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
22 có thể có các hình dạng khác nhau và một số trong số chúng yêu cầu các thuộc tính khác nhau. Bạn sẽ thấy một ví dụ về điều này khi xem phần tử
# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
22 thứ hai, tạo ra một nút gửi và là phần tử HTML cuối cùng tạo nên đoạn mã của bạn.

Gửi nút

Phần tử

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
22 thứ hai tạo nút cho phép người dùng của bạn gửi đầu vào của họ:

$ python3 -m pip install 
4

Phần tử này cũng có hai thuộc tính HTML, được đặt tên là

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
34 và
# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
42:

  • # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    34 Xác định loại phần tử đầu vào sẽ được tạo. Sử dụng giá trị
    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    44 tạo một nút cho phép bạn gửi dữ liệu biểu mẫu đi kèm trở đi.
    defines what sort of input element will be created. Using the value
    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    44 creates a button that allows you to send the bundled-up form data onwards.

  • # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    42 Xác định văn bản mà nút sẽ hiển thị. Hãy thay đổi nó để xem cách nút hiển thị văn bản đã thay đổi của bạn. defines what text the button should display. Feel free to change it to see how the button displays your changed text.

Với cái nhìn tổng quan ngắn gọn về các yếu tố HTML khác nhau và các thuộc tính của chúng trong tâm trí, giờ đây bạn hiểu rõ hơn về những gì bạn đã thêm vào mã Python của mình và những yếu tố được sử dụng để làm gì.

Thông tin mà bạn sẽ cần kết nối gửi biểu mẫu với mã bình của bạn là giá trị

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
22 phần tử đầu tiên ____ ____137,
ERROR: (gcloud.app.deploy)
You do not currently have an active account selected.
Please run:

  $ gcloud auth login

to obtain new credentials.

If you have already logged in with a different account:

    $ gcloud config set account ACCOUNT

to select an already authenticated account to use.
9, mà bạn sẽ sử dụng để truy cập giá trị đã gửi trong chức năng của bạn.

Tiếp theo, bạn sẽ học cách thay đổi mã Python của mình để xử lý chính xác đầu vào mẫu đã gửi.

Nhận đầu vào của người dùng

Trong thuộc tính

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
24 của phần tử
# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
12 của bạn, bạn đã chỉ định rằng dữ liệu của biểu mẫu HTML của bạn phải được gửi lại cho cùng một URL. Bây giờ bạn cần bao gồm các chức năng để tìm nạp giá trị trong
$ source venv/bin/activate
1. Đối với điều này, bạn cần hoàn thành hai bước:

  1. Nhập Flask Flask

    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    52 Đối tượng: Giống như nhiều khung web, Flask chuyển các yêu cầu HTTP cùng như các đối tượng toàn cầu. Để có thể sử dụng đối tượng
    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    52 toàn cầu này, trước tiên bạn cần nhập nó.
    Like many web frameworks, Flask passes HTTP requests along as global objects. In order to be able to use this global
    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    52 object, you first need to import it.

  2. Tìm nạp giá trị: Đối tượng

    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    52 chứa giá trị đã gửi và cho phép bạn truy cập vào nó thông qua cú pháp từ điển Python. Bạn cần lấy nó từ đối tượng toàn cầu để có thể sử dụng nó trong chức năng của bạn. The
    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    52 object contains the submitted value and gives you access to it through a Python dictionary syntax. You need to fetch it from the global object to be able to use it in your function.

Viết lại mã của bạn và thêm hai thay đổi này ngay bây giờ. Bạn cũng sẽ muốn thêm giá trị bị bắt ở cuối chuỗi biểu mẫu để hiển thị nó sau biểu mẫu:

$ python3 -m pip install 
5

Từ điển

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
55 chứa bất kỳ dữ liệu nào được gửi với yêu cầu Get HTTP. Nếu URL cơ sở của bạn được gọi ban đầu, không có bản gửi biểu mẫu, thì từ điển sẽ trống và bạn sẽ trả lại một chuỗi trống làm giá trị mặc định thay thế. Nếu trang được gọi thông qua việc gửi biểu mẫu, thì từ điển sẽ chứa một giá trị trong khóa
ERROR: (gcloud.app.deploy)
You do not currently have an active account selected.
Please run:

  $ gcloud auth login

to obtain new credentials.

If you have already logged in with a different account:

    $ gcloud config set account ACCOUNT

to select an already authenticated account to use.
9 và bạn có thể tìm nạp thành công nó và thêm nó vào chuỗi được trả về.

Cho nó một vòng quay! Bây giờ bạn có thể nhập một số và thấy nó được hiển thị ngay bên dưới nút biểu mẫu. Nếu bạn nhập một số mới, thì số cũ sẽ được thay thế. Bạn có thể gửi chính xác và nhận dữ liệu mà người dùng của bạn đang gửi.

Trước khi bạn chuyển sang tích hợp giá trị đã gửi với mã chuyển đổi nhiệt độ của bạn, có bất kỳ vấn đề tiềm ẩn nào bạn có thể nghĩ đến với việc triển khai này không?

Điều gì xảy ra khi bạn nhập một chuỗi thay vì một số? Hãy thử một lần.

Bây giờ nhập mã HTML ngắn

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
57 và nhấn Chuyển đổi.

Hiện tại, ứng dụng web của bạn chấp nhận bất kỳ loại đầu vào nào, có thể là một số, chuỗi hoặc thậm chí mã HTML hoặc JavaScript. Điều này cực kỳ nguy hiểm vì người dùng của bạn có thể vô tình hoặc cố tình phá vỡ ứng dụng web của bạn bằng cách nhập các loại nội dung cụ thể.

Hầu hết thời gian bạn nên tự động cho phép Flask chăm sóc các vấn đề bảo mật này bằng cách sử dụng một thiết lập dự án khác. Tuy nhiên, bây giờ bạn đang ở trong tình huống này, vì vậy, bạn nên tìm hiểu làm thế nào bạn có thể làm thủ công biểu mẫu bạn đã tạo đầu vào an toàn.

Thoát khỏi đầu vào người dùng

Lấy đầu vào từ người dùng và hiển thị lại đầu vào đó mà không cần điều tra trước những gì bạn sẽ hiển thị là một lỗ hổng bảo mật lớn. Ngay cả khi không có ý định độc hại, người dùng của bạn có thể làm những việc bất ngờ khiến ứng dụng của bạn bị phá vỡ.

Cố gắng hack hình thức đầu vào không được ghi nhận của bạn bằng cách thêm một số văn bản HTML vào nó. Thay vì nhập một số, hãy sao chép dòng mã HTML sau, dán nó vào hộp đầu vào của bạn và nhấp vào Chuyển đổi:

$ python3 -m pip install 
6

Bình chèn văn bản trực tiếp vào mã HTML, điều này khiến đầu vào văn bản này được hiểu là thẻ HTML. Do đó, trình duyệt của bạn hiển thị mã một cách nghiêm túc, như với bất kỳ HTML nào khác. Thay vì hiển thị lại đầu vào dưới dạng văn bản, bạn đột nhiên phải đối phó với một liên kết spam giáo dục sành điệu được truyền thời gian ở đây ngay từ những năm 90:

Mặc dù ví dụ này là vô hại và biến mất với việc làm mới trang của bạn, bạn có thể tưởng tượng làm thế nào điều này có thể đưa ra một vấn đề bảo mật khi các loại nội dung khác được thêm vào theo cách này. Bạn không muốn mở ra khả năng người dùng chỉnh sửa các khía cạnh của ứng dụng web của bạn mà aren có nghĩa là được chỉnh sửa.

Để tránh điều này, bạn có thể sử dụng Flask,

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
58 tích hợp, chuyển đổi các ký tự HTML đặc biệt
# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
59,
# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
60 và
# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
61 thành các biểu diễn tương đương có thể được hiển thị chính xác.

Trước tiên, bạn cần nhập

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
62 vào tập lệnh Python của mình để sử dụng chức năng này. Sau đó, khi bạn gửi biểu mẫu, bạn có thể chuyển đổi bất kỳ ký tự HTML đặc biệt nào và tạo biểu mẫu của bạn Input của bạn, Hacker không có khả năng:

$ python3 -m pip install 
7

Làm mới máy chủ phát triển của bạn và thử gửi một số mã HTML. Bây giờ nó sẽ được hiển thị lại cho bạn dưới dạng chuỗi văn bản mà bạn đã nhập.

Sau khi học cách thu thập đầu vào của người dùng và cách thoát khỏi nó, cuối cùng bạn cũng đã sẵn sàng thực hiện chức năng chuyển đổi nhiệt độ và hiển thị cho người dùng Fahrenheit tương đương với nhiệt độ Celsius mà họ đã nhập.

Xử lý đầu vào người dùng

Vì phương pháp này chỉ sử dụng một điểm cuối URL, bạn có thể dựa vào bình để gõ kiểm tra đầu vào của người dùng thông qua việc chụp thành phần đường dẫn URL như bạn đã làm trước đó. Điều này có nghĩa là bạn sẽ muốn giới thiệu lại khối

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
08 ____ ____109 của bạn từ
 * Serving Flask app "main" (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: on
 * Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 315-059-987
8 ban đầu của mã gốc.

Lần này,

 * Serving Flask app "main" (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: on
 * Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 315-059-987
8 đã giành được liên kết với một nhà trang trí
 1from flask import Flask
 2
 3app = Flask(__name__)
 4
 5@app.route("/")
 6def index():
 7    return "Congratulations, it's a web app!"
8. Đi trước và xóa dòng mã đó. Bạn sẽ gọi
 * Serving Flask app "main" (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: on
 * Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 315-059-987
8 rõ ràng từ
$ source venv/bin/activate
1 thay vì yêu cầu bình thực thi khi truy cập điểm cuối URL cụ thể được truy cập.

Sau khi xóa trình trang trí từ

 * Serving Flask app "main" (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: on
 * Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 315-059-987
8 và giới thiệu lại khối
# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
08 ____ ____109, bạn sẽ tiếp theo thêm một câu lệnh có điều kiện vào
$ source venv/bin/activate
1 để kiểm tra xem đối tượng toàn cầu
# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
52 có chứa khóa
ERROR: (gcloud.app.deploy)
You do not currently have an active account selected.
Please run:

  $ gcloud auth login

to obtain new credentials.

If you have already logged in with a different account:

    $ gcloud config set account ACCOUNT

to select an already authenticated account to use.
9 hay không. Nếu có, thì bạn muốn gọi
 * Serving Flask app "main" (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: on
 * Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 315-059-987
8 để tính toán độ Fahrenheit tương ứng. Nếu nó không có, thì bạn chỉ định một chuỗi trống cho biến
# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
77 thay thế.

Làm điều này cho phép bạn thêm giá trị của

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
77 vào cuối chuỗi HTML của bạn. Chuỗi trống giành được có thể nhìn thấy trên trang của bạn, nhưng nếu người dùng đã gửi một giá trị, thì nó sẽ hiển thị bên dưới biểu mẫu.

Sau khi áp dụng các thay đổi cuối cùng này, bạn hoàn thành mã cho ứng dụng Bình chuyển đổi nhiệt độ của mình:

$ python3 -m pip install 
8

Vì đã có khá nhiều thay đổi, nên ở đây, một đánh giá từng bước về các dòng đã chỉnh sửa:

  • Dòng 2: Bạn không sử dụng

    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    79 nữa, vì vậy bạn có thể xóa nó khỏi câu lệnh nhập. You’re not using
    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    79 anymore, so you can remove it from the import statement.

  • Các dòng 8, 11 và 12: Như trước đây, bạn đã tìm nạp giá trị do người dùng gửi qua Flask Flask Global

    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    52 đối tượng. Bằng cách sử dụng phương thức từ điển
    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    81, bạn đảm bảo rằng một chuỗi trống được trả về nếu khóa được tìm thấy. Đó là trường hợp nếu trang được tải ban đầu và người dùng đã không gửi biểu mẫu. Điều này được thực hiện trong dòng 11 và 12.
    As before, you’re fetching the user-submitted value through Flask’s global
    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    52 object. By using the dictionary method
    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    81, you assure that an empty string gets returned if the key isn’t found. That’ll be the case if the page is loaded initially and the user hasn’t submitted the form yet. This is implemented in lines 11 and 12.

  • Dòng 19: Bằng cách trả lại biểu mẫu với chuỗi trống mặc định bị kẹt vào cuối, bạn tránh hiển thị bất cứ điều gì trước khi biểu mẫu được gửi. By returning the form with the default empty string stuck to the end, you avoid displaying anything before the form has been submitted.

  • Dòng 9 và 10: Sau khi người dùng của bạn nhập giá trị và nhấp vào Chuyển đổi, cùng một trang sẽ được tải lại. Lần này,

    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    82 tìm khóa
    ERROR: (gcloud.app.deploy)
    You do not currently have an active account selected.
    Please run:
    
      $ gcloud auth login
    
    to obtain new credentials.
    
    If you have already logged in with a different account:
    
        $ gcloud config set account ACCOUNT
    
    to select an already authenticated account to use.
    
    9 và trả về giá trị liên quan. Điều này làm cho câu lệnh có điều kiện đánh giá thành
    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    84 và giá trị do người dùng cung cấp được chuyển sang
     * Serving Flask app "main" (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: on
     * Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
     * Restarting with stat
     * Debugger is active!
     * Debugger PIN: 315-059-987
    
    8.
    After your users enter a value and click Convert, the same page gets loaded again. This time around,
    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    82 finds the
    ERROR: (gcloud.app.deploy)
    You do not currently have an active account selected.
    Please run:
    
      $ gcloud auth login
    
    to obtain new credentials.
    
    If you have already logged in with a different account:
    
        $ gcloud config set account ACCOUNT
    
    to select an already authenticated account to use.
    
    9 key and returns the associated value. This makes the conditional statement evaluate to
    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    84, and the user-provided value is passed to
     * Serving Flask app "main" (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: on
     * Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
     * Restarting with stat
     * Debugger is active!
     * Debugger PIN: 315-059-987
    
    8.

  • Các dòng 24 đến 29:

     * Serving Flask app "main" (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: on
     * Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
     * Restarting with stat
     * Debugger is active!
     * Debugger PIN: 315-059-987
    
    8 Kiểm tra xem người dùng có cung cấp đầu vào hợp lệ không. Nếu giá trị được cung cấp có thể được chuyển đổi thành
    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    87, thì hàm này áp dụng mã chuyển đổi nhiệt độ và trả về nhiệt độ trong Fahrenheit. Nếu nó có thể được chuyển đổi, thì ngoại lệ
    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    88 sẽ được nâng lên và chức năng trả về chuỗi
    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    89 thay thế.
     * Serving Flask app "main" (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: on
     * Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
     * Restarting with stat
     * Debugger is active!
     * Debugger PIN: 315-059-987
    
    8 checks if the user supplied a valid input. If the provided value can be converted to a
    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    87, then the function applies the temperature conversion code and returns the temperature in Fahrenheit. If it can’t be converted, then a
    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    88 exception is raised, and the function returns the string
    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    89 instead.

  • Dòng 19: Lần này, khi bạn kết hợp biến

    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    77 đến cuối chuỗi HTML, nó chỉ vào giá trị trả về của
     * Serving Flask app "main" (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: on
     * Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
     * Restarting with stat
     * Debugger is active!
     * Debugger PIN: 315-059-987
    
    8. Điều này có nghĩa là nhiệt độ được chuyển đổi hoặc chuỗi thông báo lỗi sẽ được thêm vào HTML của bạn.
    This time, when you concatenate the
    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    77 variable to the end of the HTML string, it points to the return value of
     * Serving Flask app "main" (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: on
     * Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
     * Restarting with stat
     * Debugger is active!
     * Debugger PIN: 315-059-987
    
    8. This means that either the converted temperature or the error message string will be added to your HTML.

  • Các dòng 15 và 18: Để làm cho trang dễ sử dụng hơn, bạn cũng thêm các nhãn mô tả

    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    92 và
    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    93 vào cùng chuỗi HTML này.
    To make the page easier to use, you also add the descriptive labels
    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    92 and
    # Start with a basic flask app webpage.
    from flask_socketio import SocketIO, emit
    from flask import Flask, render_template, url_for, copy_current_request_context
    from random import random
    from time import sleep
    from threading import Thread, Event
    import requests, json
    import time
    
    __author__ = 'slynn'
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    app.config['DEBUG'] = True
    
    #turn the flask app into a socketio app
    socketio = SocketIO(app)
    
    #random number Generator Thread
    thread = Thread()
    thread_stop_event = Event()
    
    class RandomThread(Thread):
        def __init__(self):
            self.delay = 1
            super(RandomThread, self).__init__()
    
        def randomNumberGenerator(self):
            while not thread_stop_event.isSet():
                socketio.emit('newnumber', {'number': parsed}, namespace='/test')
                sleep(self.delay)
    
        def run(self):
            self.randomNumberGenerator()
    
    
    @app.route('/')
    def index():
        #only by sending this page first will the client be connected to the socketio instance
        return render_template('index.html')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        # need visibility of the global thread object
        global thread
        print('Client connected')
    
        #Start the random number generator thread only if the thread has not been started before.
        if not thread.isAlive():
            print("Starting Thread")
            thread = RandomThread()
            thread.start()
    
    @socketio.on('disconnect', namespace='/test')
    def test_disconnect():
        print('Client disconnected')
    
    
    if __name__ == '__main__':
        socketio.run(app)
    
    93 to this same HTML string.

Trang của bạn sẽ hiển thị chính xác mặc dù cách bạn thêm các chuỗi này không đại diện cho HTML hợp lệ. Điều này hoạt động nhờ sức mạnh của các trình duyệt hiện đại.

Hãy nhớ rằng nếu bạn quan tâm đến việc lặn sâu hơn vào phát triển web, thì bạn sẽ cần phải học HTML. Nhưng vì lợi ích của việc triển khai kịch bản Python của bạn trực tuyến, điều này sẽ làm tốt.

Bây giờ bạn sẽ có thể sử dụng tập lệnh chuyển đổi nhiệt độ của bạn bên trong trình duyệt của bạn. Bạn có thể cung cấp nhiệt độ Celsius thông qua hộp đầu vào, nhấp vào nút và xem kết quả Fahrenheit được chuyển đổi xuất hiện trên cùng một trang web. Vì bạn sử dụng yêu cầu HTTP Get mặc định, bạn cũng có thể thấy dữ liệu đã gửi xuất hiện trong URL.

Triển khai ứng dụng đã hoàn thành của bạn một lần nữa cho Công cụ ứng dụng Google bằng lệnh

 * Serving Flask app "main" (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: on
 * Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 315-059-987
6. Sau khi triển khai xong, hãy truy cập URL được cung cấp hoặc chạy
 * Serving Flask app "main" (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: on
 * Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 315-059-987
3 để xem ứng dụng web Python của bạn trực tiếp trên Internet. Kiểm tra nó bằng cách thêm các loại đầu vào khác nhau. Khi bạn đã hài lòng, hãy chia sẻ liên kết của bạn với thế giới.

URL của ứng dụng web chuyển đổi nhiệt độ của bạn vẫn trông giống như

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
96. Điều này không phản ánh chức năng hiện tại của ứng dụng của bạn.

Xem lại các hướng dẫn triển khai, tạo một dự án mới trên Công cụ ứng dụng Google với tên phù hợp hơn và triển khai ứng dụng của bạn ở đó. Điều này sẽ cung cấp cho bạn thực hành trong việc tạo các dự án và triển khai các ứng dụng bình của bạn cho Google App Engine.

Tại thời điểm này, bạn đã chuyển đổi thành công tập lệnh Python của mình thành một ứng dụng web Python và triển khai nó thành Google App Engine để lưu trữ trực tuyến. Bạn có thể sử dụng cùng một quy trình để chuyển đổi nhiều tập lệnh Python của mình thành các ứng dụng web.

Tạo trình tạo bài thơ của riêng bạn cho phép người dùng tạo các bài thơ ngắn bằng biểu mẫu web. Ứng dụng web của bạn nên sử dụng một trang duy nhất với một biểu mẫu chấp nhận nhận được yêu cầu. Bạn có thể sử dụng mã ví dụ này để bắt đầu hoặc bạn có thể viết của riêng bạn.

Nếu bạn muốn tìm hiểu thêm về những gì bạn có thể làm với Google App Engine, thì bạn có thể đọc về việc sử dụng các tệp tĩnh và thêm tệp CSS vào ứng dụng web Python của bạn để cải thiện diện mạo tổng thể của nó.

Lưu trữ mã trực tuyến của bạn có thể làm cho nó có thể truy cập được cho nhiều người qua internet. Đi trước và chuyển đổi các tập lệnh yêu thích của bạn thành các ứng dụng bình và hiển thị chúng với thế giới.

Sự kết luận

Bạn đã đề cập rất nhiều nền tảng trong hướng dẫn này! Bạn đã bắt đầu với một tập lệnh Python cục bộ và biến nó thành một ứng dụng bình được triển khai đầy đủ, thân thiện với người dùng mà hiện đang được lưu trữ trên Google App Engine.

Trong khi làm việc thông qua hướng dẫn này, bạn đã học được:

  • Cách ứng dụng web cung cấp dữ liệu qua Internetweb applications provide data over the Internet
  • Cách tái cấu trúc tập lệnh Python của bạn để bạn có thể lưu trữ trực tuyếnrefactor your Python script so you can host it online
  • Cách tạo ứng dụng bình cơ bảnFlask application
  • Cách thoát thủ công đầu vào của người dùngescape user input
  • Cách triển khai mã của bạn cho Công cụ ứng dụng Googledeploy your code to Google App Engine

Bây giờ bạn có thể lấy các kịch bản Python địa phương của bạn và cung cấp chúng trực tuyến cho cả thế giới để sử dụng. Nếu bạn muốn tải xuống mã hoàn chỉnh cho ứng dụng bạn đã xây dựng trong hướng dẫn này, thì bạn có thể nhấp vào liên kết bên dưới:

Nếu bạn muốn tìm hiểu thêm về phát triển web với Python, thì bây giờ bạn sẽ được trang bị tốt để thử nghiệm các khung web Python như Flask và Django. Hãy tiếp tục phát huy!

Xem bây giờ hướng dẫn này có một khóa học video liên quan được tạo bởi nhóm Python thực sự. Xem nó cùng với hướng dẫn bằng văn bản để hiểu sâu hơn về sự hiểu biết của bạn: Triển khai tập lệnh Python của bạn trên web bằng bình This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Deploy Your Python Script on the Web With Flask

Làm cách nào để chạy tệp .py trong bình?

Tạo và chạy một ứng dụng bình tối thiểu#..
Trong mã VS, hãy tạo một tệp mới trong thư mục dự án của bạn có tên app.py bằng cách sử dụng tệp> mới từ menu, nhấn Ctrl+N hoặc sử dụng biểu tượng tệp mới trong chế độ xem Explorer (hiển thị bên dưới) ..
Trong App.Py, thêm mã để nhập bình và tạo một thể hiện của đối tượng bình ..

Bạn có thể chạy tập lệnh Python trong tập lệnh Python không?

Dòng đầu tiên của 'Nhập Python_2' trong tập lệnh Python_1, sẽ gọi tập lệnh Python_2 thứ hai.Bất cứ khi nào bạn muốn chạy một tập lệnh Python từ một tập lệnh khác, bạn sẽ cần nhập tên chính xác của tập lệnh Python mà bạn muốn gọi.you'll need to import the exact name of the Python script that you'd like to call.

Làm cách nào để chạy một tệp .py trực tiếp?

Để chạy các tập lệnh Python bằng lệnh Python, bạn cần mở một dòng lệnh và nhập từ python, hoặc python3 nếu bạn có cả hai phiên bản, theo sau là đường dẫn đến tập lệnh của bạn, giống như thế này: $ python3 hello.py xin chàoThế giới!Nếu mọi thứ hoạt động ổn, sau khi bạn nhấn Enter, bạn sẽ thấy cụm từ Hello World!open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World! If everything works okay, after you press Enter , you'll see the phrase Hello World!

Làm cách nào để chạy kịch bản Python ở bất cứ đâu?

Để làm cho các tập lệnh Python có thể chạy được từ bất kỳ vị trí nào trong Windows:..
Tạo thư mục để đặt tất cả các tập lệnh Python của bạn vào. ....
Sao chép tất cả các tập lệnh Python của bạn vào thư mục này ..
Thêm đường dẫn vào thư mục này trong biến hệ thống "đường dẫn" Windows: ....
Chạy hoặc khởi động lại "Lời nhắc Anaconda".
Gõ "your_script_name.py".