Django
项目
1.项目系统设计:
menu:
菜单设计
playground:
游戏界面
settings:
设置界面
2.项目文件结构:
3.项目初始化
将所添加的app
的urls
,views
,models
删除,创建urls
,views
,models
,static
文件夹, 便于管理
在settings里添加
1 2 3 4 5 6 import osSTATIC_ROOT = os.path.join(BASE_DIR, 'static' ) STATIC_URL = "/static/" MEDIA_ROOT = os.path.join(BASE_DIR, 'media' ) MEDIA_URL = "/media/"
Redis
配置
安装django_redis
1 pip install django_redis
配置settings.py
1 2 3 4 5 6 7 8 9 10 CACHES = { 'default' : { 'BACKEND' : 'django_redis.cache.RedisCache' , 'LOCATION' : 'redis://127.0.0.1:6379/1' , "OPTIONS" : { "CLIENT_CLASS" : "django_redis.client.DefaultClient" , }, }, } USER_AGENTS_CACHE = 'default'
启动redis-server
1 sudo redis-server /etc/redis/redis.conf
Redis
命令
1 2 3 4 5 6 from django.core.cache import cachecache.keys('*' ) #查找数据库中的关键字,支持正则表达式(返回的是关键字) cache.set('ym' ,1 ,5 ) #设置关键字,第三个参数表示多久过期,?None 是永不过期(单位是秒) cache.has_key('' ) #查询关键字是否存在(返回的是True 或者False ) cache.get('' ) #获取关键字对应的值 cache.delete('' ) #删除一个关键字
授权登录过程
联机对战
配置 channels_redis
1.安装channels_redis
1 pip install channels_redis
2.配置 acapp/asgi.py
内容如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 import osfrom channels.auth import AuthMiddlewareStackfrom channels.routing import ProtocolTypeRouter, URLRouterfrom django.core.asgi import get_asgi_applicationfrom game.routing import websocket_urlpatternsos.environ.setdefault('DJANGO_SETTINGS_MODULE' , 'acapp.settings' ) application = ProtocolTypeRouter({ "https" : get_asgi_application(), "websocket" : AuthMiddlewareStack(URLRouter(websocket_urlpatterns)) })
3. acapp/settings.py
在INSTALLED_APPS
中添加channels
,添加后如下所示:
1 2 3 4 5 6 7 8 9 10 INSTALLED_APPS = [ 'channels' , 'game.apps.GameConfig' , 'django.contrib.admin' , 'django.contrib.auth' , 'django.contrib.contenttypes' , 'django.contrib.sessions' , 'django.contrib.messages' , 'django.contrib.staticfiles' , ]
然后在文件末尾添加:
1 2 3 4 5 6 7 8 9 ASGI_APPLICATION = 'acapp.asgi.application' CHANNEL_LAYERS = { "default" : { "BACKEND" : "channels_redis.core.RedisChannelLayer" , "CONFIG" : { "hosts" : [("127.0.0.1" , 6379 )], }, }, }
4.配置 game/routing.py
这一部分的作用相当于https
的urls
。内容如下:
1 2 3 4 from django.urls import pathwebsocket_urlpatterns = [ ]
5.编写 game/consumers
这一部分的作用相当于https
的views
。
参考示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 from channels.generic.websocket import AsyncWebsocketConsumerimport jsonclass MultiPlayer (AsyncWebsocketConsumer ): async def connect (self ): await self.accept() print ('accept' ) self.room_name = "room" await self.channel_layer.group_add(self.room_name, self.channel_name) async def disconnect (self, close_code ): print ('disconnect' ) await self.channel_layer.group_discard(self.room_name, self.channel_name) async def receive (self, text_data ): data = json.loads(text_data) print (data)
6.启动django_channels
在~/acapp
目录下执行:
1 daphne -b 0.0.0.0 -p 5015 acapp.asgi:application