在 Android Studio 中运行 Python Web 服务器

Posted

技术标签:

【中文标题】在 Android Studio 中运行 Python Web 服务器【英文标题】:Run Python webserver in AndroidStudio 【发布时间】:2021-06-16 17:59:14 【问题描述】:

我想创建包含 Python 网络服务器的 androidTVApp。我正在使用 python 库 Chaquopy。像 print HelloWorld 这样的简单 python 脚本可以工作。我是新手,但我认为我必须在服务类中运行网络服务器才能在后台运行。它不起作用。首先,我尝试在 ShowWebsiteActivity.java 中运行 Python,但 webview 只显示空白页面。所以,这就是我尝试在服务中调用和运行 Python 脚本的原因。 Python 文件有效,我尝试在我的电脑上运行它,但在 AdnroidStudio 中没有。它引发此错误 - 无法将字节对象转换为 java.lang.String。如何在后台运行 Python 网络服务器? 这是我的代码:Java 类

public class ShowWebsiteActivity extends FragmentActivity 

WebView web;
TextView textView;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    
    // CALLING SERVICES
    startService(new Intent(this,StartPythonWebServer.class)); 
    
    setContentView(R.layout.activity_website);
    web = findViewById(R.id.webView);
    WebSettings webSettings = web.getSettings();
    webSettings.setBuiltInZoomControls(true);
    webSettings.setjavascriptEnabled(true);
    webSettings.setAllowContentAccess(true);
    webSettings.setDomStorageEnabled(true);
    web.setWebViewClient(new Callback());
    web.loadUrl("http://10.0.2.2:8080/");

    textView = findViewById(R.id.DateTime);
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE, dd-MM-yyyy hh:mm:ss a");
    String dateTime = simpleDateFormat.format(calendar.getTime());
    textView.setText(dateTime);

    final Button logout = findViewById(R.id.logout);
    logout.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View v) 
            web.loadUrl("http://10.0.2.2:8080/menu");
        
    );

服务类

public class StartPythonWebServer extends Service 

@Nullable
@Override
public IBinder onBind(Intent intent) 
    return null;


@Override
public int onStartCommand(Intent intent, int flags, int startId) 
    Toast.makeText(this, "Service started by user.", Toast.LENGTH_LONG).show();
    Python py = Python.getInstance();
    py.getModule("webserver").callAttr("start");

    return START_STICKY;


@Override
public void onDestroy() 
    super.onDestroy();
    Toast.makeText(this, "Service destroyed by user.", Toast.LENGTH_LONG).show();

Python

from flask import Flask, render_template, url_for, redirect, render_template, request
import os
from werkzeug.utils import secure_filename
app = Flask(__name__,
            static_folder='static',
            template_folder='templates')

@app.route('/')
def main():
    return render_template('login.html')

@app.route('/menu', methods=['GET', 'POST'])
def menu():
    return render_template('menu.html')

@app.route('/content', methods=['GET', 'POST'])
def content():
return render_template('index.html')

def start():
    app.run(debug=True, host='0.0.0.0', port=8080)

'''
if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=8080)
'''

【问题讨论】:

【参考方案1】:

无法将字节对象转换为 java.lang.String

这可能是由this issue 引起的:click 访问 stdout 的方式与 Chaquopy 将其重定向到 Logcat 的方式不兼容。我们将在下一个版本的 Chaquopy 中解决这个问题。同时,您可以通过将以下代码添加到 Python 文件的开头来解决此问题:

import sys
for stream in [sys.stdout, sys.stderr]:
    def write_override(s, write_original=stream.write):
        if not isinstance(s, str):
            raise TypeError()
        return write_original(s)
    stream.write = write_override

【讨论】:

以上是关于在 Android Studio 中运行 Python Web 服务器的主要内容,如果未能解决你的问题,请参考以下文章

android studio怎么运行apk包

android studio怎么在打开的虚拟机上运行不了

Android Studio中运行Android模拟器

用android studio 编写的程序可以在ios上运行吗

在Android Studio中运行Android App:无法创建密钥库

Android studio运行程序出现两个apk