简体   繁体   中英

Flask only working as expected in debug mode

I'm creating a desktop application using electron and flask. When I attempt to send a selected path (selected by the user via a folder select dialog. Using electron I am able to get the full path and not something like C:/fake_path. This is because electron provides the full path via .files[0].path) to python using flask, I never receive a response or caught an error (the main.logPython function is never called in either branch following the rq).

However, if I include app.debug = True in the python file to turn on the Flask debugger, it runs as expected and prints out the path. Essentially the python code is not even being reached unless I put it into debug mode.

edit: I know this is true because I've attempted to run python code other than just the return (like creating a new file) and it's never run.

edit #2: It seems this problem is related to the admin.js file. If I attempt to make a similar connection in the main.js file I get the result that I expect, however if I use the same code in the admin.js file I get no response as stated above.

Hopefully I've provided enough information. If you need anything else please let me know.

Sorry for any formatting issues with the JavaScript code, I'm very new to it so I just threw it into dirty markup to clean it up a bit.

calling JavaScript code (admin.js)

const remote = require("electron").remote;
const main = remote.require("./main.js");
var importButton = document.getElementById("importButton");
if (importButton.addEventListener) {
    importButton.addEventListener("click", importPackages, false);
} else if (importButton.attachEvent) {
    importButton.attachEvent("onclick", importPackages);
}

function importPackages() {
    var importDirectory = document.getElementById("importDirectory").files[0].path;
    var rq = require('request-promise');
    var mainAddr = 'http://localhost:5000';
    rq(mainAddr + "/import_packages/" + importDirectory).then(function(htmlString) {
        if (htmlString != "false") {
            main.logPython(htmlString);
        }
    }).catch(function(err) {
        main.logPython('request not sent');
    })
}

python code (database_handler.py)

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import Flask, request
import sqlite3

app = Flask(__name__)
# app.debug = True

@app.route("/")
def hello():
    return "true"


@app.route("/login/<username>/<password>")
def login(username, password):
    conn = sqlite3.connect("hict.sqlite")
    cursor = conn.cursor()
    cursor.execute("SELECT firstname, lastname, userclass FROM credentials "
                   "WHERE username=? AND password=? LIMIT 1;",
                   (username, password))
    data = cursor.fetchall()
    if len(data) == 0:
        return "false"
    else:
        return "|".join(map(str, data[0]))


@app.route("/import_packages/<path:import_directory>")
def import_packages(import_directory):
    return import_directory


if __name__ == "__main__":
    app.run(host='127.0.0.1', port=5000)

Main JavaScript code (main.js)

const electron = require("electron");
const {app, BrowserWindow} = electron;
app.on('window-all-closed', () => {
    app.quit();
})
app.on('ready', () => {
    var subpy = require('child_process').spawn('python', ['./database_handler.py']);
    //var subpy = require('child_process').spawn('./dist/hello.exe');
    var rq = require('request-promise');
    var mainAddr = 'http://localhost:5000';
    var openWindow = () => {
        let win = new BrowserWindow({
            width: 1920,
            height: 1080
        });
        win.maximize();
        win.setMenu(null);
        win.loadURL(`file://${__dirname}/login.html`);
        win.on('closed', () => {
            win = null;
            subpy.kill('SIGINT');
        })
    }
    var startUp = () => {
        rq(mainAddr).then(function(htmlString) {
            console.log('server started!');
            openWindow();
        }).catch(function(err) {
            console.log('waiting for the server start...');
            startUp();
        })
    }
    startUp();
})
exports.logPython = (returnData) => {
    console.log(returnData);
}

It looks like you are using admin.js as code in your UI, so it is in a renderer process. Your main.js looks like it is running in your project's main process. I am unsure if it actually works to require main.js in admin.js for this case. Why not try using ipc to send the data from your UI to the main process (main.js)?

Also, to eliminate an obvious answer... console.log() in the main process (main.js) will print out in your terminal as you expect. console.log() in the renderer process (admin.js) prints out in the dev console. On windows I think you open that with by clicking on your UI and then ctrl+shift+i. So if you didn't know this, it might be working but you don't see it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM