Commit 68e6d3b0 authored by gaoming's avatar gaoming

项目迁移

parent ae009c19
This diff is collapsed.
This source diff could not be displayed because it is too large. You can view the blob instead.
This diff is collapsed.
<?xml version="1.0" encoding="utf-8"?>
<gm_rpcd_config>
<info config_name="app" version="1.0"/>
<config name="application_name" value="geoserver"/>
<config name="service_list">
<element value="geoserver"/>
</config>
<config name="initializer_list">
<element value="geoserver.geoserver_injection"/>
<element value="home.views" />
</config>
</gm_rpcd_config>
\ No newline at end of file
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'geoserver.settings')
django.setup()
\ No newline at end of file
This diff is collapsed.
# coding=utf-8
import threading
import time
import logging
import json
import uuid
import random
import datetime
from django.http import parse_cookie
from django.conf import settings
from django.utils.http import cookie_date
from django.contrib.sessions.middleware import SessionMiddleware
from gm_types.gaia import PLATFORM_CHOICES
from libs.exception_info import get_exception_info, get_func_args
exception_logger = logging.getLogger('exception_logger')
profile_logger = logging.getLogger('profile_logger')
class TrackingMiddleware(object):
"""set/get tracking cookie."""
def _parse_xcx_cookies(self, http_cookies):
"""小程序cookie解析还原。
由于小程序头部cookie是小写:cookie,http后端set-cookie到浏览器会响应为Cookie,
造成小程序上传两个cookie导致直接拼接,sessionid变成不可用状态。比如小程序:
cookie:a=b Cookie:c=d 到后端就变成了a='b,c=d'。
"""
_cookies = {}
for name, v in http_cookies.items():
error_cookie = '{}={}'.format(name, v)
raw_cookie = error_cookie.replace(',', ';')
cookies = parse_cookie(raw_cookie)
for k, v in cookies.items():
_cookies[k] = v
return _cookies
def process_request(self, request):
"""check if tracking cookie exist"""
if request.GET.get("platform", '') == PLATFORM_CHOICES.WECHATXCX:
cookies = self._parse_xcx_cookies(request.COOKIES)
for name, v in cookies.items():
request.COOKIES[name] = v
if settings.TRACKING_COOKIE_NAME in request.COOKIES:
request._has_tracking_cookie = True
request.tracking_cookie = request.COOKIES[settings.TRACKING_COOKIE_NAME]
else:
request._has_tracking_cookie = False
request.tracking_cookie = uuid.uuid1().hex + str(random.randrange(1, 10000))
def process_response(self, request, response):
if not request._has_tracking_cookie:
expires_time = time.time() + settings.TRACKING_COOKIE_AGE
expires = cookie_date(expires_time)
response.set_cookie(
settings.TRACKING_COOKIE_NAME,
request.tracking_cookie,
max_age=settings.TRACKING_COOKIE_AGE,
expires=expires,
)
return response
class LoggingMiddleware(object):
def process_request(self, request):
request.start_time = time.time()
def process_response(self, request, response):
execute_time = time.time() - request.start_time
path = request.get_full_path()
gm_request_id = request.META.get('HTTP_X_GM_REQUEST_ID')
try:
items = {}
if request.method == 'GET':
items = request.GET.dict()
elif request.method == 'POST':
items = request.POST.dict()
items = json.dumps(items)
except:
items = ''
profile_logger.info(
json.dumps(
{
'timestamp': datetime.datetime.fromtimestamp(
request.start_time
).strftime('%Y-%m-%dT%H:%M:%S+08:00'),
'request_method': request.method,
'path': path,
'execute_time': execute_time,
'items': items,
'gm_request_id': gm_request_id
}
, ensure_ascii=True, encoding='utf-8'
)
)
return response
def process_exception(self, request, exception):
gm_request_id = request.META.get('HTTP_X_GM_REQUEST_ID')
exc = get_exception_info()
func_args = get_func_args()
exception_logger.info(
json.dumps(
{
'gm_request_id': gm_request_id,
'stacktrace': exc,
'func_args': func_args,
'timestamp': datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S+08:00'),
}
, ensure_ascii=True, encoding='utf-8'
)
)
class TrackingCityMiddleware(object):
def process_request(self, request):
current_city_id = request.GET.get('current_city_id', '')
request.logger.app(tracking_id=request.tracking_cookie, current_city_id=current_city_id)
# coding=utf-8
"""
Django settings for geoserver project.
Generated by 'django-admin startproject' using Django 2.2.5.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
import socket
import helios
import helios.rpc
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 't&@8d5g(i!ka$7*r=&e@#lfv@wi-q0xawn^#_f^q0w$ly)tcnm'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ["*"]
RPC_INVOKER = helios.rpc.create_default_invoker(debug=DEBUG)
#*********************************************Redis Config******************************
REDIS_HOST="172.17.40.145"
REDIS_PASSWORD="zi1jlhVHtH8MGNqB"
REDIS_PORT=6379
REDIS_DB=7
#***************************************************************************************
QQ_MAP_KEYS = [
'QVMBZ-KZFRJ-VQ5F6-FMJIJ-SCJN6-WNFFS',
'2RJBZ-EWTW3-ANB3A-3O6KS-SDYRK-EQFFO',
'2LZBZ-K353F-ZQKJG-JGT7Z-PQYD2-YVBLE',
'D7FBZ-SRGKG-AU3QI-IGMXR-63EU3-3PBOA',
'H52BZ-JH2WX-EAB4T-TXW23-SNBLQ-GNFNQ',
'RL2BZ-CASW3-MJ53C-3JCUR-IEGRO-TABLU',
'NJIBZ-L2H3U-ZWLV6-4W3PK-H7DFF-OSFUM',
'ZOBBZ-FP2WX-CA74G-TZC24-MPSL7-22BD4',
'TENBZ-AZ53P-JRTDP-LUIQ2-KNVE6-XNF4X',
'L7GBZ-JKMWP-HKJDV-LQPEC-QQ2M7-D6BAT',
]
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'home'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'geoserver.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'geoserver.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
# RPC_URL = 'http://rpc.test.gengmei.cc/api/'
# RPC_URL = 'http://rpc.test.gengmei.cc/api/'
# RPC_SECRET = 'basic:6o9sVEB6+H5U61rfZpVMioWcRRoU32uazNE3h18kwcAqOMPVdjmvQ72XxZVNLNl6RSACrgLeD7xrKYsxL1iZ6A=='
# RPC_INVOKER = helios.rpc.RPCFactory(RPC_URL, RPC_SECRET, debug=DEBUG, debug_unwrap_checker_raise_exception=False,
# debug_dump_curl=True, use_batch=False).create_invoker()
#RPC_INVOKER = helios.rpc.create_default_invoker(debug=DEBUG)
#如果是我的电脑就加载本地配置文件
import socket
if socket.gethostname()=="AppledeMacBook-Pro.local":
from .settings_local import *
\ No newline at end of file
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
#**********************************Celery Config*************************************************
CELERY_BROKER_URL = 'redis://127.0.0.1:6379/0' # Broker配置,使用Redis作为消息中间件
CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/0' # BACKEND配置,这里使用redis
CELERY_RESULT_SERIALIZER = 'json' # 结果序列化方案
#***********************************Redis Config***********************************************
REDIS_HOST="127.0.0.1"
REDIS_PASSWORD=""
REDIS_PORT=6379
REDIS_DB=0
#***********************************************************************************
\ No newline at end of file
"""geoserver URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('home/', include('home.urls'),name='home'),
]
"""
WSGI config for geoserver project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'geoserver.settings')
application = get_wsgi_application()
from django.contrib import admin
# Register your models here.
from django.apps import AppConfig
class HomeConfig(AppConfig):
name = 'home'
from django.db import models
# Create your models here.
from django.test import TestCase
# Create your tests here.
from django.urls import include, path,re_path
from . import views
app_name="home"
#(?P<sub_name>[a-z0-9]+/)?
urlpatterns =[
re_path('nearly_hospitals',views.nearly_hospitals),
]
\ No newline at end of file
import redis
import logging
from django.conf import settings
from django.shortcuts import render
from math import radians, cos, sin, asin, sqrt
from django.http import HttpResponse,JsonResponse
import random
import requests
import ipdb
from gm_rpcd.all import bind,RPCDFaultException
#from rpc.decorators import bind_context, bind
r = redis.Redis(host=settings.REDIS_HOST, port=settings.REDIS_PORT,db=settings.REDIS_DB,password=settings.REDIS_PASSWORD,decode_responses=True)
rpc_client =settings.RPC_INVOKER
# Create your views here.
@bind('geoserver/home/nearly_hospitals')
def nearly_hospitals(q_lat,q_lng,radis=500,unit="km",count=20):
'''
查询最近医院
@q_lnt 经度
@q_lat 纬度
@radis 方圆多少公里
'''
#查询的经纬度
#q_lat,q_lng=40.001930265172,116.4871890387796
#数据缓存时间,现在为24小时
cache_key="hospital_location"
cache_diuration=24*60*60
#ipdb.set_trace()
if not r.exists(cache_key):
print("地理位置信息过期---,重新拿取---")
locations = rpc_client['api/hospital/location']().unwrap()
#将地理位置信息加入redis缓存
for item in locations:
lat=item.get("baidu_loc_lat") if item.get("baidu_loc_lat") else item.get("google_loc_lat")
lng=item.get("baidu_loc_lng") if item.get("baidu_loc_lng") else item.get("google_loc_lng")
try:
r.geoadd(cache_key,float(lng),float(lat),item.get("id"))
except Exception as e:
print(e)
pass
r.expire(cache_key,cache_diuration)
result=r.georadius(cache_key,q_lng,q_lat,radis,unit,withdist=True,count=20)
data={
"result":True,
"data":result,
"message":""
}
return data
def get_location_by_address(request,address):
"""由地址获获取经纬度坐标
:param address: 目标地址 '西城区西什库大街8号(近地安门西大街)
:return: 经纬度信息 {"lng": 116.306735, "lat": 39.982951}
"""
QQ_MAP_KEY = random.choice(settings.QQ_MAP_KEYS)
params = {
'address': address,
'key': QQ_MAP_KEY,
'output': 'json',
}
url = 'http://apis.map.qq.com/ws/geocoder/v1'
response = requests.get(url, params=params)
result = response.json()
if result['status'] == 0:
return result['result']['location']
else:
return None
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'geoserver.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
appnope==0.1.0
attrs==19.1.0
backcall==0.1.0
cached-property==1.5.1
certifi==2019.6.16
chardet==3.0.4
contextlib2==0.5.5
decorator==4.4.0
Django==2.2.4
falcon==1.1.0
gevent==1.4.0
gm-config==0.1.3
gm-logging==0.7.4
gm-protocol==7.10.25
gm-rpcd==0.2.2
gm-tracer==0.1.2
gm-types==7.70.65
greenlet==0.4.15
gunicorn==19.9.0
helios==0.7.0
idna==2.8
ipdb==0.12.2
ipython==7.8.0
ipython-genutils==0.2.0
jedi==0.15.1
jsonschema==3.0.2
kafka-python==1.3.1
monotonic==1.5
msgpack-python==0.4.8
mysqlclient==1.4.2
parso==0.5.1
pexpect==4.7.0
pickleshare==0.7.5
prompt-toolkit==2.0.9
protobuf==3.6.0
psutil==5.6.3
ptyprocess==0.6.0
Pygments==2.4.2
pyrsistent==0.15.4
python-mimeparse==1.6.0
pytz==2019.2
PyYAML==3.11
raven==5.32.0
redis==3.3.8
requests==2.22.0
six==1.12.0
sqlparse==0.3.0
traitlets==4.3.2
urllib3==1.25.3
verlib==0.1
wcwidth==0.1.7
wrapt==1.11.2
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment