Django(python)简单实现android的服务器端
Django(python)简单实现android的服务器端
1. 所需工具
PyCharm--python编辑工具,这里要写Django,因此必须是专业版,社区版没有此功能。
MySql--登录信息需要存储到数据库里面。
Android Studio--用于手机端代码的编写。
2. 服务器端的实现
2.1. 新建一个Django项目,命名为:androidSevers
2.2. 为androidSevers添加一个APP模块:Login_sever
python manage.py startapp Login_sever
完成后效果如图所示
2.3. 数据库连接及其setting.py配置
添加APP
连接MySQL(大小写严格区分)
DATABASES = { ‘default‘: { ‘ENGINE‘: ‘django.db.backends.mysql‘, ‘NAME‘: ‘androidsevers‘, ‘USER‘: ‘root‘, ‘PASSWORD‘: ‘123456‘, ‘PORT‘: 3306, ‘HOST‘: ‘‘, } }
2.4. 通过设计model.py,映射到数据库。
from django.db import models # Create your models here. class Login(models.Model): ID=models.AutoField(primary_key=True) username=models.CharField(max_length=25,verbose_name=‘用户名‘) password=models.CharField(max_length=25,verbose_name=‘密码‘) adminname=models.CharField(max_length=25,verbose_name=‘用户姓名‘)
2.5. 将model.py映射到数据库
在pycharm下面的终端下执行
创建迁移文件
python manage.py makemigrations
将迁移文件写入数据库
python manage.py migrate
执行完成后,在数据库里显示,如图所示。
在数据库里写入一条记录,用于测试。如
2.5. 配置路由信息,urls.py
from django.contrib import admin from django.urls import path from Login_sever import views urlpatterns = [ path(‘admin/‘, admin.site.urls), path(‘login/‘,views.login_view) ]
2.6. 对数据的操作views.py
from django.core.exceptions import ObjectDoesNotExist from django.http import HttpResponse from django.shortcuts import render from Login_sever.models import Login import json def login_view(request): if request.method==‘POST‘: username=request.POST.get(‘username‘) password=request.POST.get(‘password‘) date_error={ ‘username‘: username, ‘adminname‘: ‘‘, ‘code‘:‘错误,用户不存在‘, ‘Status Code‘: 404 } try: user=Login.objects.get(username=username) if user.password==password: data={ ‘username‘:user.username, ‘adminname‘:user.adminname, ‘code‘: ‘成功‘, ‘Status Code‘: 200 } return HttpResponse(json.dumps(data), content_type=‘application/json‘) else: date_error = { ‘username‘: username, ‘adminname‘: ‘‘, ‘code‘: ‘密码错误‘, ‘Status Code‘: 404 } return HttpResponse(json.dumps(date_error), content_type=‘application/json‘) except ObjectDoesNotExist: return HttpResponse(json.dumps(date_error),content_type=‘application/json‘) else: return HttpResponse(‘GET请求无效‘)
2.7. 启动服务器
2.7.1. 查询服务器的IP地址
ipconfig
2.7.2. 在setting里面配置IP地址
将这里修改为你的IP地址
2.7.3. 启动服务器
在pycharm的终端中输入
python manage.py runserver 192.168.0.104:8000
服务器端完成
3. 客户端的实现
3.1. 用android创建一个工程:androidclient
3.2. 新建一个LoginActivity
3.3. 新建一个类Login_cs
完成后如图所示
3.4. 在Login_cs里面写入
public class Login_cs { /** * username : admin * adminname : 李东阳 * code : 成功 * Status Code : 200 */ private String username; private String adminname; private String code; @SerializedName("Status Code") private int _$StatusCode185; // FIXME check this code public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getAdminname() { return adminname; } public void setAdminname(String adminname) { this.adminname = adminname; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public int get_$StatusCode185() { return _$StatusCode185; } public void set_$StatusCode185(int _$StatusCode185) { this._$StatusCode185 = _$StatusCode185; } }
3.5. 修改配置文件AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.androidclient"> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".LoginActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".MainActivity"></activity> </application> </manifest>
3.6. 添加依赖
implementation ‘com.squareup.okhttp3:okhttp:3.10.0‘ implementation ‘com.google.code.gson:gson:2.6.2‘
3.7. 设置activity_login.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".LoginActivity"> <EditText android:layout_marginTop="35dp" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入用户名" android:gravity="center" android:textSize="25dp" android:id="@+id/tvUserName"/> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入密码" android:textSize="25dp" android:gravity="center" android:inputType="textPassword" android:id="@+id/tvPassword"/> <Button android:id="@+id/btnLogin" android:layout_marginTop="25dp" android:layout_width="wrap_content" android:layout_gravity="center" android:background="#03A9F4" android:text="登录" android:textColor="#fff" android:textSize="25dp" android:paddingLeft="35dp" android:paddingRight="35dp" android:layout_height="wrap_content"/> </LinearLayout>
3.8. 设置LoginActivity.java
package com.example.androidclient; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.google.gson.Gson; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class LoginActivity extends AppCompatActivity implements View.OnClickListener { private EditText tvUserName; private EditText tvPassword; private Button btnLogin; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); initView(); } private void initView() { tvUserName = (EditText) findViewById(R.id.tvUserName); tvPassword = (EditText) findViewById(R.id.tvPassword); btnLogin = (Button) findViewById(R.id.btnLogin); btnLogin.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnLogin: submit(); break; } } private void submit() { // validate String tvUserNameString = tvUserName.getText().toString().trim(); if (TextUtils.isEmpty(tvUserNameString)) { Toast.makeText(this, "请输入用户名", Toast.LENGTH_SHORT).show(); return; } String tvPasswordString = tvPassword.getText().toString().trim(); if (TextUtils.isEmpty(tvPasswordString)) { Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show(); return; } // TODO validate success, do something InternetSever(tvUserNameString,tvPasswordString); } private void InternetSever(String username,String password) { OkHttpClient client = new OkHttpClient(); FormBody body = new FormBody.Builder() .add("username", username) .add("password", password) .build(); final Request request = new Request.Builder() .url("http://192.168.0.104:8000/login/") .post(body) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Toast.makeText(LoginActivity.this, "网络异常,请稍后再试!", Toast.LENGTH_SHORT).show(); } @Override public void onResponse(Call call, Response response) throws IOException { final String date=response.body().string(); runOnUiThread(new Runnable() { @Override public void run() { Gson gson=new Gson(); Login_cs login_cs=gson.fromJson(date,Login_cs.class); if (login_cs.get_$StatusCode185()==200){ Toast.makeText(LoginActivity.this, "欢迎登录,"+login_cs.getAdminname(), Toast.LENGTH_SHORT).show(); startActivity(new Intent(LoginActivity.this,MainActivity.class)); }else { Toast.makeText(LoginActivity.this, login_cs.getCode(), Toast.LENGTH_SHORT).show(); tvPassword.setText(""); tvUserName.setText(""); } } }); } }); } }
客户端完成
4.测试
完成,如有问题晴留言给我哦!
服务器端源码:https://github.com/ldy731729142/androidSevers
客户端源码:https://github.com/ldy731729142/AndroidClient