#!/usr/bin/python
# -*- coding: UTF-8 -*-
import json
from django.http import HttpResponse
def HttpResponseJsonCORS(request,s):
response = HttpResponse(s,content_type="application/json")
try:
origin = request.META['HTTP_ORIGIN']
except:
origin = 'http://127.0.0.1'
if origin.find("192.168") >0 :
pass
elif origin.find("127.0.0.1") >0 :
pass
# else:
# origin = front_url
print origin
response["Access-Control-Allow-Origin"] = "%s"%(origin)
response["Access-Control-Allow-Credentials"] = "true"
response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
response["Access-Control-Max-Age"] = "1000"
response["Access-Control-Allow-Headers"] = "*"
return response
def HttpResponseCORS(request, s):
response = HttpResponse(s)
try:
origin = request.META['HTTP_ORIGIN']
except:
origin = 'http://127.0.0.1'
if origin.find("192.168") > 0:
pass
elif origin.find("127.0.0.1") > 0:
pass
# else:
# origin = front_url
# sql = "insert into sql_log (`sql`) values ('%s')"%(origin)
# print sql
# db.executesql(sql)
response["Access-Control-Allow-Origin"] = "%s" % (origin)
response["Access-Control-Allow-Credentials"] = "true"
response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
response["Access-Control-Max-Age"] = "1000"
response["Access-Control-Allow-Headers"] = "*"
return response
def index(request):
# 原始数据
rows = (('apollo', 'male', '164.jpeg'), ('apollo', 'male', ''))
# 表头
names = 'username gender pic'.split()
# URL公共部分
fs_url = 'http://www.baidu.com/'
# 新数据列表
L = []
for e in rows:
L1 = list(e)
pic = e[2]
if pic == '':
L1[2] = "%suser_pic/default.jpg" % (fs_url)
else:
L1[2] = "%suser_pic/small_%s" % (fs_url, pic)
L.append(L1)
print L
# 用zip组合列表套字典
"""
[{'username': 'apollo', 'gender': 'male', 'pic': 'http://www.baidu.com/user_pic/small_164.jpeg'},
{'username': 'apollo', 'gender': 'male', 'pic': 'http://www.baidu.com/user_pic/default.jpg'}]
"""
data = [dict(zip(names, d)) for d in L]
print data
# 对上面结果Json序列化
"""
[{"username": "apollo", "gender": "male", "pic": "http://www.baidu.com/user_pic/small_164.jpeg"},
{"username": "apollo", "gender": "male", "pic": "http://www.baidu.com/user_pic/default.jpg"}]
"""
info = json.dumps(data, ensure_ascii=False)
print info
# 组合返回结果,返给前端
"""
response = {
"errcode": 0,
"errmsg": "获取用户列表成功",
"readLog":[{"username": "apollo", "gender": "male", "pic": "http://www.baidu.com/user_pic/small_164.jpeg"},
{"username": "apollo", "gender": "male", "pic": "http://www.baidu.com/user_pic/default.jpg"}]
}
"""
s = """
{
"errcode": 0,
"errmsg": "获取用户列表成功",
"readLog":%s
}
""" % (info)
print s
return HttpResponseJsonCORS(request,s)
原文地址:https://www.cnblogs.com/apollo1616/p/10418466.html
时间: 2024-10-11 15:20:37