时间:2021-05-22
最近在做游戏服务分层的时候,一直想把mysql的访问独立成一个单独的服务DBGate,原因如下:
当然坏处也是有的:
不过总的来说,还是利大于弊,所以最终还是决定搭建DBGate
当然,我们不可能去手工挨个写每个库表对应的restful服务,值得庆幸的是django和flask都提供了对应的解决方案,我们一个个介绍.
Flask
参考链接: flask-restless
flask-restless使用方法比较简单,我直接贴一下代码即可:
# -*- coding: utf-8 -*-
import datetime
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_restless import APIManager
app = Flask(__name__)
db = SQLAlchemy(app)
restless = APIManager(app, flask_sqlalchemy_db=db)
class User(db.Model):
"""
user
"""
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(255), unique=True, nullable=False)
password = db.Column(db.String(255), nullable=False)
create_time = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow)
login_time = db.Column(db.DateTime)
restless.create_api(User, methods=['GET', 'POST', 'DELETE', 'PATCH', 'PUT'], results_per_page=100)
db.create_all()
if __name__ == '__main__':
app.run(port=25000)
# -*- coding: utf-8 -*-
import datetime
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_restless import APIManager
app = Flask(__name__)
db = SQLAlchemy(app)
restless = APIManager(app, flask_sqlalchemy_db=db)
class User(db.Model):
"""
user
"""
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(255), unique=True, nullable=False)
password = db.Column(db.String(255), nullable=False)
create_time = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow)
login_time = db.Column(db.DateTime)
restless.create_api(User, methods=['GET', 'POST', 'DELETE', 'PATCH', 'PUT'], results_per_page=100)
db.create_all()
if __name__ == '__main__':
app.run(port=25000)
其对应的restful操作如下:
获取用户列表: GET /user
添加用户: POST /user
获取单个用户: GET /user/1
覆盖单个用户: PUT /user/1
修改单个用户: PATCH /user/1
获取用户列表: GET /user
添加用户: POST /user
获取单个用户: GET /user/1
覆盖单个用户: PUT /user/1
修改单个用户: PATCH /user/1
注意:
Django
参考链接: Django REST framework
Django用起来要更复杂一些,也因为django版自带了一个可视化的操作页面,如下:
1. 在settings中添加:
REST_FRAMEWORK = { # Use hyperlinked styles by default. # Only used if the `serializer_class` attribute is not set on a view. 'DEFAULT_MODEL_SERIALIZER_CLASS': 'rest_framework.serializers.HyperlinkedModelSerializer', # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ #'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly', 'rest_framework.permissions.IsAdminUser', ]} REST_FRAMEWORK = { # Use hyperlinked styles by default. # Only used if the `serializer_class` attribute is not set on a view. 'DEFAULT_MODEL_SERIALIZER_CLASS': 'rest_framework.serializers.HyperlinkedModelSerializer', # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ #'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly', 'rest_framework.permissions.IsAdminUser', ]}2. 通过startapp建立一个app: demo
3. 修改demo的models:
4. 在demo下新建serializers.py
from rest_framework import serializers
from models import User
5. 在demo下修改views.py
from django.shortcuts import renderfrom rest_framework import viewsetsfrom serializers import UserSerializerfrom models import Userclass UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer from django.shortcuts import renderfrom rest_framework import viewsets from serializers import UserSerializerfrom models import User class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer6. 在demo下新建urls.py
import os.pathfrom django.conf.urls import patterns, include, urlfrom django.conf.urls.static import staticfrom django.conf import settingsimport viewsfrom rest_framework import routersappname = os.path.basename(os.path.dirname(os.path.abspath(__file__)))router = routers.DefaultRouter()router.register('users', views.UserViewSet, appname)urlpatterns = patterns('', url(r'^', include(router.urls)),) import os.pathfrom django.conf.urls import patterns, include, urlfrom django.conf.urls.static import staticfrom django.conf import settingsimport views from rest_framework import routers appname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) router = routers.DefaultRouter()router.register('users', views.UserViewSet, appname) urlpatterns = patterns('', url(r'^', include(router.urls)),)7. 在mysite.urls下include demo.urls和rest_framework.urls
urlpatterns = patterns('', url(r'^demo/', include('demo.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))) urlpatterns = patterns('', url(r'^demo/', include('demo.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')))8. 执行初始化数据操作:
python manage.py syncdb python manage.py syncdb之后访问: http://127.0.0.1:8000/demo 即可看到如下界面了:
对应的测试代码如下:
import jsonimport requestsfrom urlparse import urljoinBASE_URL = 'http://127.0.0.1:16500/'AUTH = ('admin', 'admin')def test_get_user_list(): rsp = requests.get(urljoin(BASE_URL, '/demo/users/'), auth=AUTH, headers={ 'Accept': 'application/json' }) assert rsp.okdef test_post_user_list(): json_data = dict( password=0, nick='oo', create_time='2014-03-3T03:3:3' ) rsp = requests.post(urljoin(BASE_URL, '/demo/users/'), auth=AUTH, headers={ 'Accept': 'application/json', 'Content-Type': 'application/json', }, data=json.dumps(json_data)) assert rsp.okdef test_get_user(): rsp = requests.get(urljoin(BASE_URL, '/demo/users/1'), auth=AUTH, headers={ 'Accept': 'application/json', 'Content-Type': 'application/json', }) assert rsp.okdef test_put_user(): json_data = dict( password=100, nick='xx', create_time='2014-03-3T03:3:3' ) # 注意最后的 / rsp = requests.put(urljoin(BASE_URL, '/demo/users/1/'), auth=AUTH, headers={ 'Accept': 'application/json', 'Content-Type': 'application/json', }, data=json.dumps(json_data), ) assert rsp.ok, rsp.status_codeDjango REST framework 是严格区分PUT和PATCH的,这一点和flask-restless 不一样,需要注意。
OK,就这样。
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
这是一个轻量级框架,专为快速开发RESTful接口而设计。如果你和我一样,厌倦了使用传统的MVC框架编写微服务或者前后端分离的API接口,受不了为了一个简单接口
jersey是基于Java的一个轻量级RESTful风格的WebServices框架。以下我基于IDEA实现Restful完整Demo。1.创建maven-we
springmvc实现Restful返回xml格式数据最近,想在自己的小项目中搭建一个Restful风格的服务接口api,项目用的springmvc3,听说sp
SwaggerSwagger是一种和语言无关的规范和框架,用于定义服务接口,主要用于描述RESTful的API。它专注于为API创建优秀的文档和客户端库。支持S
一.简介SpringCloud是基于Restful的远程调用框架,引入Ribbon负载均衡组件后还需要客户端使用RestTemplate调用远程接口,操作起来还