Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed Docker #1

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions .env

This file was deleted.

2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
SECRET_KEY=YourSecretKey
DOMAIN=YourDomain
143 changes: 143 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,146 @@
/venv/
/.idea/
/config.chat.migrations/
### Python template
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# extra
.idea/
config/db.sqlite3
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
FROM python:3.10

ENV PYTHONUNBUFFERED 1
ENV DJANGO_ENV dev
ENV DOCKER_CONTAINER 1
Expand All @@ -7,7 +8,6 @@ COPY ./requirements.txt /code/requirements.txt
RUN pip install -r /code/requirements.txt

COPY . /code/
COPY c
WORKDIR /code/

EXPOSE 8000
Expand Down
37 changes: 23 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,41 +1,50 @@
## Simple web chat on Websockets and Django



## If you want to change settings, you should edit the env file

# Simple web chat on Websockets and Django


Launch
------
----------

```
```bash
git clone https://github.com/BenitoSwaggolini/WebChat.git
cd WebChat
python -m venv venv
.\venv\Scripts\activate
pip install -r requirements.txt
cd config
python manage.py migrate
python manage.py runserver
```

#### Create file `.env` or delete ```.example``` from ```.env.example```

#### Fill in the data in the file `.env`

Docker
------
### Example:

```dotenv
SECRET_KEY=MySecretKey
DOMAIN=127.0.0.1:8000
```
https://github.com/BenitoSwaggolini/WebChat.git
docker-compose up -d

#### Run
```
python manage.py runserver
```

Docker
------

```bash
https://github.com/BenitoSwaggolini/WebChat.git
cd WebChat
```

```
docker-compose up -d
```

Opportunities:
------


* `chat/<room_name>` - Chat
* `log` - Authorization
* `item` - Registration
Expand Down
20 changes: 14 additions & 6 deletions config/chat/consumers.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
from channels.generic.websocket import AsyncWebsocketConsumer
import json

from channels.generic.websocket import AsyncWebsocketConsumer


class ChatRoomConsumer(AsyncWebsocketConsumer):
def __init__(self, *args, **kwargs):
super().__init__(args, kwargs)
self.room_group_name = None
self.room_name = None

async def connect(self):
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.room_group_name = f'chat_{self.room_name}'
Expand All @@ -22,19 +28,21 @@ async def disconnect(self, code):

async def receive(self, text_data=None, bytes_data=None):
text_data_in_json = json.loads(text_data)

message = text_data_in_json['message']
username = text_data_in_json['username']

await self.channel_layer.group_send(
self.room_group_name,
{'message': message,
'username': username,
'type': 'chat_message'}
{
'message': message,
'username': username,
'type': 'chat_message'
}
)

async def chat_message(self, event):
message = event['message']
username = event['username']
await self.send(text_data=json.dumps({'message': message, 'username': username,}))


await self.send(text_data=json.dumps({'message': message, 'username': username}))
2 changes: 1 addition & 1 deletion config/chat/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,4 @@ class LoginForm(AuthenticationForm):

class Meta:
model = User
fields = ['username', 'password']
fields = ['username', 'password']
2 changes: 2 additions & 0 deletions config/chat/routing.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from django.urls import re_path

from .consumers import ChatRoomConsumer

websocket_urlpatterns = [
re_path(r'ws/chat/(?P<room_name>\w+)/$', ChatRoomConsumer.as_asgi())
]
27 changes: 27 additions & 0 deletions config/chat/static/js/messages.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const roomName = JSON.parse(document.getElementById("room-name").textContent);
const username = JSON.parse(document.getElementById("username").textContent);

document.querySelector('#submit').onclick = function (e) {

const messageInputDom = document.querySelector('#input');
const message = messageInputDom.value;

ChatSocket.send(JSON.stringify({
'message': message,
'username': username,
}));

messageInputDom.value = '';
};

const ChatSocket = new WebSocket(
'ws://' + window.location.host + '/ws/chat/' + roomName + '/'
);

ChatSocket.onmessage = function (e) {
const data = JSON.parse(e.data)

console.log(data)

document.querySelector('#chat-messages').value += (data.username + ': ' + data.message + '\n')
}
42 changes: 42 additions & 0 deletions config/chat/templates/chat/chatroom.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
{% extends 'base.html' %}
{% load static %}

{% block css %}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z"
crossorigin="anonymous"/>
{% endblock css %}


{% block title %}
Hello
{% endblock title %}

{% block content %}
<div class="container">
<div class="mb-3">
<h1>Chat "{{ room_name }}"</h1>
<textarea class="form-control" id="chat-messages" rows="15" disabled></textarea>
</div>

<input id="input" type="text" size="146"/>
<input id="submit" type="button" class="btn btn-primary" value="send"/>
</div>

{{ room_name|json_script:"room-name" }}
{{ request.user.username|json_script:"username" }}

<script src="{% static 'js/messages.js' %}"></script>

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"
integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"
crossorigin="anonymous"></script>

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
crossorigin="anonymous"></script>
{% endblock content %}
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
{% extends 'base.html' %}
{% block title %}


{% endblock %}
{% block title %}
{% endblock title %}

{% block content %}

Expand All @@ -18,4 +17,4 @@ <h2>HOW TO JOIN THE CHAT:</h2>

{{DOMAIN}}/chat/ + your_chatroom_name

{% endblock %}
{% endblock content %}
11 changes: 11 additions & 0 deletions config/chat/templates/chat/register.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{% extends 'base.html' %}

{% block content %}
<form class="mega" method="post">
{% csrf_token %}

{{ form.as_p }}

<button class="form-button" type="submit">Send</button>
</form>
{% endblock content %}
Loading