CentOS 7 初始设置
将用户加入sudoers
usermod -aG wheel newuser
设置开机启动网络
cd /etc/sysconfig/network-scripts ls -a vi ifcfg-ens33
将ONBOOT=no 改成ONBOOT=yes 保存后退出。
How to Install Python 3 on CentOS 7
sudo yum install centos-release-scl sudo yum install rh-python36 scl enable rh-python36 bash python --version sudo yum groupinstall 'Development Tools'
Creating a Virtual Environment
python -m venv my_project_venv source my_project_venv/bin/activate
After activating the environment, the shell prompt will be prefixed with the name of the environment.
Django改变模型:
-
编辑 models.py 文件,改变模型。
-
运行
python manage.py makemigrations
为模型的改变生成迁移文件。 -
运行
python manage.py migrate
来应用数据库迁移。
Json转换为Python对象
class Object: def __init__(self, _dict): self.__dict__ = _dict jsondata = json.loads(data, object_hook=Object)
Python操作符
Ordering | a < b | lt(a, b) |
---|---|---|
Ordering | a <= b | le(a, b) |
Equality | a == b | eq(a, b) |
Difference | a != b | ne(a, b) |
Ordering | a >= b | ge(a, b) |
Ordering | a > b | gt(a, b) |
It's simple to create a read-only serializer for converting HighScore instances into primitive data types.
class HighScoreSerializer(serializers.BaseSerializer): def to_representation(self, obj): return { 'score': obj.score, 'player_name': obj.player_name }
We can now use this class to serialize single HighScore instances:
@api_view(['GET']) def high_score(request, pk): instance = HighScore.objects.get(pk=pk) serializer = HighScoreSerializer(instance) return Response(serializer.data)
Or use it to serialize multiple instances:
@api_view(['GET']) def all_high_scores(request): queryset = HighScore.objects.order_by('-score') serializer = HighScoreSerializer(queryset, many=True) return Response(serializer.data)
Defining a Serializer
Create a file named serializers.py
inside the api
app directory. Put the following codes into it.
from rest_framework import serializersclass HelloWorldSerializer(serializers.Serializer): name = serializers.CharField(required=True, max_length=6) age = serializers.IntegerField(required=False, min_value=10, default=10)
We’re creating a HelloWorldSerializer
which extends serializers.Serializer
. We’re defining two fields on this serializer –
-
name
is aCharField
so it accepts string. It has amax_length
of 6. -
age
is an optional integer field. The value must be at least 10 if provided. If not provided, default value will be 10.
With this serializer setup, let’s modify our view to use it.
from .serializers import HelloWorldSerializerclass HelloWorldView(APIView): def get(self, request): return Response({"message": "Hello World!"}) def post(self, request): serializer = HelloWorldSerializer(data=request.data) if serializer.is_valid(): valid_data = serializer.data name = valid_data.get("name") age = valid_data.get("age") return Response({"message": "Hello {}, you're {} years old".format(name, age)}) else: return Response({"errors": serializer.errors})
We pass the request.data
as the data
parameter to HelloWorldSerializer
so it can read all the request data and parse them. Then we check if the serializer is valid. If you have used Django Forms, this will feel very similar. If the serializer is valid, that means we have a valid set of data available. So we can take the value of name and age and show a pretty message. On the other hand, if the serializer is not valid, we can pass the serializer.errors
back to the client, which will contain elaborate error messages.
def timestamp(strTime): dt = datetime.strptime(strTime, "%Y-%m-%d %H:%M:%S") return 1000*dt.timestamp() def timestring(timestamp): dt = datetime.fromtimestamp(timestamp) return datetime.strptime(dt, "%Y-%m-%d %H:%M:%S")