Something about CentOS and Django

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操作符

Orderinga < blt(a, b)
Orderinga <= ble(a, b)
Equalitya == beq(a, b)
Differencea != bne(a, b)
Orderinga >= bge(a, b)
Orderinga > bgt(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 a CharField so it accepts string. It has a max_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")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值