1.基本环境配置
windows 10
安装python3.7.2
安装虚拟环境(避免环境之间相互污染)
C:Usersws>pip install virtualenv
pip install virtualenvwrapper-win
# 创建基于python3.7的虚拟环境
mkvirtualenv.bat python37_django2
# 进入虚拟环境
workon python37_django2
# 安装基本的依赖插件
pip install django==2.1.2
pip install requests
pip install requests geoip2
# 进入d:/python 这个源码目录,在指定位置创建项目
django-admin startproject simple_ip_server
cd simple_ip_server
python manage.py startapp ipserver
2.设置IDE工具开发环境
用pycharm打开项目
3.配置django
配置基本的环境,添加app
设置 语言、时区 环境
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
编写api的视图
ipserver/views.py # coding:utf-8 from django.http import HttpResponse,JsonResponse from django.views import View import geoip2.database class IpServer(View): def get(self, request): reader = geoip2.database.Reader(r'D:pythonsimple_ip_serveripserverGeoLite2-City.mmdb') ipaddress = request.GET.get('ipaddress', '') if not ipaddress: return JsonResponse({'errorcode':-1, 'errmsg': 'ip地址不能为空'}) response = reader.city(ipaddress) country = response.country.iso_code cityname = response.city.name data = {'country':country, 'city':cityname} return JsonResponse({'errorcod':0, 'errmsg': 'success', 'data': data})
# 设置urls 路由信息
ipserver/urls.py
# _*_ coding:utf-8 _*_ # __author__ == 'jack' # __date__ == '2020-12-30 10:41 AM' from django.urls import path from .views import IpServer urlpatterns = [ path('ip/', IpServer.as_view()) ]
在总路由 simple_ip_server/urls.py 中引入
from django.contrib import admin from django.urls import path, include from ipserver import urls as ipserver_urls urlpatterns = [ path('admin/', admin.site.urls), path('', include(ipserver_urls)) ]
# 启动服务器
(python37_django2) D:pythonsimple_ip_server>python manage.py runserver
# 测试