我的项目中已经使用了mysql,现在设计了两个表想要采用mongodb数据库进行存储。
步骤如下(mongodb安装启动在https://www.cnblogs.com/huanhuaqingfeng/p/11188024.html中查看)
1,安装mongoengine
pip install mongoengine
在django中,mongoengine是django与mongodb数据库的连接器
2, 修改settings.py
DATABASES = {
‘default‘: {
‘ENGINE‘: ‘django.db.backends.mysql‘,
‘NAME‘: ‘builddatabase‘,
‘USER‘: ‘root‘,
‘PASSWORD‘: ‘likeshe‘,
‘HOST‘: ‘127.0.0.1‘,
‘PORT‘: ‘3306‘,
},
‘db1‘: {
‘ENGINE‘:None,
}
}
import mongoengine #导入mongoengine
cOnn= mongoengine.connect("Print_Analysis") ##Print_Analysis ,我的mongodb数据库的名字
3,在我的应用Print_Analysis的models.py 中添加表类
import mongoengine
class log_info(mongoengine.Document):
fun_name=mongoengine.StringField(max_length=100)
dir_name = mongoengine.StringField(max_length=100)
log_name = mongoengine.StringField(max_length=100)
path = mongoengine.StringField(max_length=255)
status = mongoengine.StringField(max_length=16)
case_num=mongoengine.IntField()
half_case_num = mongoengine.IntField()
fail_case_num = mongoengine.IntField()
line_num = mongoengine.IntField()
case_ids = mongoengine.ListField()
class case_info(mongoengine.Document):
funtion = mongoengine.StringField(max_length=255)
exe_status = mongoengine.StringField(max_length=16)
line_start = mongoengine.IntField()
line_end = mongoengine.IntField()
error_count = mongoengine.IntField()
level = mongoengine.IntField()
sucess_num = mongoengine.IntField()
fail_num = mongoengine.IntField()
status_info = mongoengine.ListField()
4,在Print_Analysis的view.py 中添加测试代码
def anlaysis_result_test():
var = log_info.objects.create(fun_name="123", dir_name="456", log_name="11.log", path="/usr/local/cc.log", status="sucess",
case_num=0, half_case_num=0,fail_case_num=0,line_num=0,case_ids=None)
print(var)
return {‘status‘: ‘already‘}
def index(request):
logger.info("request.method=%s" ,request.method)
#logger.info("request.body=%s" ,request.body)
logger.info("content_type=%s",request.content_type)
logger.info( "user=%s",request.user.username)
logger.info( "is_authenticated=%d",request.user.is_authenticated())
logger.info( "request.path=%s",request.path)
if not request.user.is_authenticated():
return HttpResponseForbidden()
if request.method==‘POST‘:
body = eval(request.body)
op_type = str(body[‘op_type‘])
if op_type == ‘anlaysis_result_test‘:
result=anlaysis_result_test()
return JsonResponse(result)
5,url路由,Print_Analysis添加在urls.py和settings.py中搞定,这里不说了。(可以查看https://www.cnblogs.com/huanhuaqingfeng/p/11101751.html)
6,python测试代码
def anlaysis_test():
data = {}
data[‘op_type‘] = "anlaysis_result_test"
respOnse= httprequest.post(url_path + "print_analysis/", json=data)
print response.text
if __name__ == ‘__main__‘:
anlaysis_test()
7,查看数据库
执行完测试后,查看数据库
./mongo进入shell
show dbs 显示所有存在的mongodb数据库
use Print_Analysis 切换到我的Print_Analysis 数据库
show tables 显示Print_Analysis中的表(又叫集合)
db.log_info.find() 查看集合log_info中的数据
Django操作mongodb