xxxxxxxxxx
# create django project in my case
my project name is "project" and app name is "app"
pip install channels
# setting.py
INSTALLED_APPS = [
'channels',
'app'
]
ASGI_APPLICATION = "project.asgi.application"
# app/consumers.py
from channels.generic.websocket import AsyncWebsocketConsumer
import json
class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
# Accepts the WebSocket connection
await self.accept()
async def disconnect(self, close_code):
# Handles WebSocket disconnection
pass
async def receive(self, text_data):
# Handles data received from WebSocket
text_data_json = json.loads(text_data)
message = text_data_json['message']
# Echoes the received message back to the client
await self.send(text_data=json.dumps({
'message': message
}))
# app/routing.py
from . import consumers
from django.urls import path
websocket_urlpatterns = [
path("ws/chat/", consumers.ChatConsumer.as_asgi()),
]
# project/asgi.py
import os
import django
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from app.routing import websocket_urlpatterns
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
django.setup()
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(
URLRouter(
websocket_urlpatterns
)
),
})
# run
# Using Daphne
daphne -p 8000 project.asgi:application
# Or using Uvicorn
uvicorn project.asgi:application --port 8000
xxxxxxxxxx
# This is a basic Flask Tutorial
# First of all, if something doesn't work, you messed up.
# Too start of, make a project folder and install flask with a venv or just normally.
# You can install flask with this command: pip install Flask
# (type this into you're terminal)
# I f you get an error message, it is because you a, dont have python3 installed,
# b: youre on a mac that has Python3 and python2 installed (this is probably the case)
# If you dont have python3 installed then go ahead and install it. If it is case b, then type in
# pip3 install Flask
# Now, lets start by making a file named app.py
# You can return basic html or text when returning in the
# Hello World function. The @app.route('/') defines that the function
# Will return at the page '/'. Debug mode is turned on on and the website
# Will run at 0.0.0.0:5000 aka localhost:5000.
from flask import Flask #Import Flask
from flask import render_template #Import render template function
app = Flask(__name__)
@app.route('/')
def hello_world():
return '''<h1>Welcome to Flask!</h1><a href=" /about">About Me!</a>'''
# You can also return a Template. For that, make a Templates folder
# and create a file named about.html inside of the Templates folder
# html file contents (copy and paste it without the hashtags):
#<html>
# <body>
# <h1>About Me</h1>
# <p>Hi, this is me, I am a Python programmer who is currently learning Flask!</p>
# <a href="/">Home</a>
# </body>
#</html>
# (You can edit it if you want)
#Just for you info, you your Project folder should look like this:
# ProjectFolder:
# app.py
# Templates:
# about.html
# Lets make a site at localhost:5000/about and use the template we created
@app.route('/about')
def about():
return render_template("about.html") # You can do this with every html file in the templates folder
#If you would like to have the same page with 2 diffrent urls (this works with as many as you want)
#You can do this:
@app.route('/page1')
@app.route('/page2')
def page1andpage2():
return 'Page1 and pag2 are now the same!'
#ps: you dont have to name the function page1andpage2
#you can name every function as you like. It doesn't matter.
#The only thing that matters about the url is the decorator (@app.route('blabla'))
#You can now acces this site on localhost:5000/page1 and on localhost:5000/page2 and they are both the same.
#Since I dont want to make this "Grepper Tutorial" I am prabably going to make a 2cnd part if guys like this
if __name__ == '__main__':
app.debug = True
app.run("0.0.0.0", 5000 , debug = True) #If you want to run youre website on a diffrent port,
#change this number ^
xxxxxxxxxx
from flask import Flask
app = Flask('app')
@app.route('/')
def hello_world():
return 'Hello, World!'
app.run(host='0.0.0.0', port=8080)
xxxxxxxxxx
# Copy Paste ( Python Flask Server Setup ) easily
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello_world():
return "<p>Hello, World!</p>"
if __name__ == "__main__":
app.run(debug=True)
xxxxxxxxxx
$ curl https://bootstrap.pypa.io/get-pip.py | python
xxxxxxxxxx
Are you are a python developer? Good.
Flask is a simple and easy to use framework for python, I really like it.
xxxxxxxxxx
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField
from wtforms.validators import DataRequired, Length
class ManufacturerForm(FlaskForm):
name = StringField('Name', validators=[DataRequired(), Length(max=100)])
country = StringField('Country', validators=[DataRequired(), Length(max=100)])
continent = StringField('Continent', validators=[DataRequired(), Length(max=100)])
established_year = IntegerField('Established Year', validators=[DataRequired()])