0

i am experimenting with flask and have a basic web page setup that gives me a data field to fill in. it all works ok, but i am having a problem with sending data via a socket connection to a server. the code is below:

from flask import Flask, render_template, request
import socket
import sys

app = Flask(__name__)

app.static_folder = 'static'

HOST, PORT = '', 8888


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


@app.route('/success', methods=['POST'])
def success():
    if request.method == 'POST':
        if request.form['Update'] == 'Update':
            messsage_name = request.form["message_name"]

            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as soc:
                # connect to server if we have a post
                soc.connect((HOST, PORT))
                soc.sendall(bytes(messsage_name + "\n", "utf-8"))
    return render_template("index.html")


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

I want to open the socket once then send data via it each time the update button is pressed, at present the only way i can get it to work is keep opening the socket as in the above code in success. I don't want the socket to close until the flask app quits.

whats the best way to achieve my goal

thanks

1
  • I tried but could not understand what you actually want. Can you try again? Commented Aug 24, 2017 at 8:43

1 Answer 1

2

I think your title is wrong. In your example there is no use of socketIO library. For using socketIO in your flask application, you need to install the library like this:

pip install flask-socketio

And then you can import it in your python file as:

from flask_socketio import SocketIO, emit

You can then use socketIO and emit some messages/data to your web page.

By the way your sockets, initialized as before, will live as long as your Flask server is on. More information available over there.

If your goal is to use the Python sockets, then you have to edit your question title.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.