文章目录
第8章 运维提升专题之部署篇
Nginx, WSGI, Flask之间的关系
Nginx:Hey,WSGI,我刚收到了一个请求,我需要你作些准备,然后由Flask来处理这个请求。
WSGI:OK,Nginx。我会设置好环境变量,然后将这个请求传递给Flask处理。
Flask:Thanks WSGI!给我一些时间,我将会把请求的响应返回给你。
WSGI:Alright,那我等你。
Flask:Okay,我完成了,这里是请求的响应结果,请求把结果传递给Nginx。
WSGI:Good job!Nginx,这里是响应结果,已经按照要求给你传递回来了。
Nginx:Cool,我收到了,我把响应结果返回给客户端。大家合作愉快~
8-2 Django依赖服务的高可用
自定义类,实现两种api的替换功能
import logging
import datetime
from thirdparty import juhe
from thirdparty.weather import heweather, CommonWeatherResult
logger = logging.getLogger('django')
class WeatherAPIProxy:
@classmethod
def ha_request(cls, cityname, timeout):
try:
data = juhe.weather(cityname, timeout)
except Exception as e:
logger.error("Request juhe weather API timeout. HARequest switch to hefeng weather.")
data = heweather.HeWeather.get_weather(cityname, timeout)
data = data.to_dict()
return data
if __name__ == '__main__':
print(WeatherAPIProxy.ha_request('北京', 1))
在view视图层调用api替换为能够实api代理池的类
class WeatherView(View, CommonResponseMixin):
def get(self, request):
if not utils.auth.already_authorized(request):
response = self.wrap_json_response({}, code=ReturnCode.UNAUTHORIZED)
else:
data = []
open_id = request.session.get('open_id')
user = User.objects.filter(open_id=open_id)[0]
cities = json.loads(user.focus_cities)
for city in cities:
# result = juhe.weather(city.get('city'))
result = WeatherAPIProxy.ha_request(city.get('city'),
timeout=settings.HA_TIMEOUT)
result['city_info'] = city
data.append(result)
response = self.wrap_json_response(data=data, code=ReturnCode.SUCCESS)
return JsonResponse(data=response, safe=False)
def post(self, request):
data = []
received_body = request.body.decode('utf-8')
received_body = json.loads(received_body)
print(received_body)
cities = received_body.get('cities')
for city in cities:
result = juhe.weather(city.get('city'))
result['city_info'] = city
data.append(result)
response_data = self.wrap_json_response(data)
return JsonResponse(data=response_data, safe=False)
uWSGI的优点
##利用uwsgi文件启动
8-6 Django Nginx+uWSGI部署
需要在settings里设置static目录
8-7 Django HTTPS部署
http vs https
以文件整数配置Nginx
配置Nginx支持https
8-8 Nginx 部署高可用服务
配置权重,模拟 均衡负载