Deploying Python script PyInstaller and Flask - python

I have a simple python script (myScript.py) that exposes some API for other apps to consume like this:
.....
app = Flask(__name__)
#app.route("/myURL")
def abc():
...
return someJSON
I used PyInstaller and generated the dist directory. It contains:
myScript* file and myScript.app/ directory
In my dev machine this is how I run my python script:
export FLASK_APP=myScript.py
flask run
and then from my browser I can reach my API like so:
localhost:5000/myURL
My question is now how can I run the generated self contained executable on user target machine. I know this is a trivial question but I can not find it in the documentation.
Is my user suppose to "export" and "flask run" on the target machine similar to the way I run it in my dev environment?

Related

Run local commands with Fabric

My environments are based on windows with vagrant or docker as the actual environments. I'd like to set up a quick way of ad hoc deploying stuff directly from windows though, it would be great if I could just run
fab deploySomething
And that would for example locally build an react app, commit and push to the server. However I'm stuck at the local bit.
My setup is:
Windows 10
Fabric 2
Python 3
I've got a fabfile.py set up with a simple test:
from fabric import Connection, task, Config
#task
def deployApp(context):
config = Config(overrides={'user': 'XXX', 'connect_kwargs': {'password': 'YYY'}})
c = Connection('123.123.123.123', config=config)
# c.local('echo ---------- test from local')
with c.cd('../../app/some-app'):
c.local('dir') #this is correct
c.local('yarn install', echo=True)
But I'm just getting:
'yarn' is not recognized as an internal or external command, operable program or batch file.
you can replace 'yarn' with pretty much anything, I can't run a command with local that works fine manually. With debugging on, all i get is:
DEBUG:invoke:Received a possibly-skippable exception: <UnexpectedExit: cmd='cd ../../app/some-app && yarn install' exited=1>
which isn't very helpful...anyone came across this? Any examples of local commands with fabric I can find seem to refer to the old 1.X versions
To run local commands, run them off of your context and not your connection. n.b., this drops you to the invoke level:
from fabric import task
#task
def hello(context):
with context.cd('/path/to/local_dir'):
context.run('ls -la')
That said, the issue is probably that you need the fully qualified path to yarn since your environment's path hasn't been sourced.

Executing bash commands from flask application

Application Details: Ubuntu 16.04 + flask + nginx + uwsgi
I am trying to execute a bash command from flask application.
#app.route('/hello', methods=('GET', 'POST'))
def hello():
os.system('mkdir my_directory')
return "Hello"
The above code run successfully but doesn't create any directory. Also it creates directory on my local which doesn't have any nginx level setup.
I also tried following ways:
subprocess.call(['mkdir', 'my_directory']) # Throws Internal server error
subprocess.call(['mkdir', 'my_directory'],shell=True) # No error but directory not created
subprocess.Popen(['mkdir', 'my_directory']) # Throws Internal server error
subprocess.Popen(['mkdir', 'my_directory'],shell=True) # No error but directory not created
Do I need any nginx level configuration changes.
Finally I got the point. I followed Python subprocess call returns “command not found”, Terminal executes correctly
.
What I was missing was absolute path of mkdir. When I executed subprocess.call(["/bin/mkdir", "my_directory"]), it makes the directory successfully.
The above link contains complete details.
Also I would be thankful if anyone will describe the reason that why I need to specify absolute path for mkdir.
Thanks to all. :)

How to create a environment-application on aws beanstalk for a python2.7.14 program using aws eb console?

I am completely new to AWS, and MacOS too. However, I am trying to create simple python apps in aws beanstalk. I got their default demo app- (the one that comes as an option while creating an environment/application) working. I followed this tutorial, and the code works locally (python 2.7.14).
But when I upload this application.py and requirements.txt via a zip, the compiled application shows health 'ok' but 'internal server error' when I load the application url.
I dont know how to debug or even what to debug as the code is quite straightforward: it is mostly an incompatible environment issue.
So, I'm looking everywhere how to make my AWSEB environment a python2.7 instead of python3.4 that its giving me, for both preconfigured docker python and preconfigured python platforms.
I am confused. How do I make my AWSEB environment / application a python 2.7.14, the one I use locally and is working well?
For reference, here is my code:
from flask import Flask
# print a nice greeting.
def say_hello(username = "World"):
return '<p>Hello %s!</p>\n' % username
# some bits of text for the page.
header_text = '''
<html>\n<head> <title>EB Flask Test</title> </head>\n<body>'''
instructions = '''
<p><em>Hint</em>: This is a RESTful web service! Append a username
to the URL (for example: <code>/Thelonious</code>) to say hello to
someone specific.</p>\n'''
home_link = '<p>Back</p>\n'
footer_text = '</body>\n</html>'
# EB looks for an 'application' callable by default.
application = Flask(__name__)
# add a rule for the index page.
application.add_url_rule('/', 'index', (lambda: header_text +
say_hello() + instructions + footer_text))
# add a rule when the page is accessed with a name appended to the site
# URL.
application.add_url_rule('/<username>', 'hello', (lambda username:
header_text + say_hello(username) + home_link + footer_text))
# run the app.
if __name__ == "__main__":
# Setting debug to True enables debug output. This line should be
# removed before deploying a production app.
application.debug = True
application.run()
requirements.txt
click==6.7
Flask==1.0.2
itsdangerous==0.24
Jinja2==2.10
MarkupSafe==1.0
Werkzeug==0.14.1
I'm running into path issues while installing the AWSEB cli- so please restrict your answers to using the console. Thank you.
If you need a different version of the platform for your application, you need to specify using a mechanism elastic beanstalk provides, ie through config.yml file. You need to create a config.yml file with environment/platform requirements and place the file under .elasticbeanstalk folder at base folder of your application.
You can see the config.yml setup and format here
And there are many supported platforms.
how do I make my aws eb environment/application a python2.7.14
Based on the above document you need to specify the following in config.yml file:
global: default_platform: 64bit Amazon Linux 2018.03 v2.7.1 running
Python 2.7
Different config files help to customize the EB config/environment. More here

Running a Python function from Ansible script

I have a Django project hosted on a remote server. This contains a file called tmp_file.py. There's a function called fetch_data() inside that file. Usually I follow the below approach to run that function.
# Inside Django Project
$ python manage.py shell
[Shell] from tmp_file import feth_data
[Shell] fetch_data()
Also the file doesn't contain __name__ section. So can't run as a stand alone script. What's the best way to perform this task using Ansible. I couldn't find anything useful from Ansible docs.
There's --command switch for shell django-admin command.
So you can try in Ansible:
- name: Fetch data
command: "django-admin shell --command='from tmp_file import feth_data; fetch_data()'"
args:
chdir: /path/to/tmp_file

Running Python scripts on local machine

I am trying to run a simple hello world example in python that runs against mongodb. I've set up mongo, bottle and pymong and have the following script inside C:\Python27\Scripts:
import bottle
import pymongo
#bottle.route('/')
def index()
from pymongo import Connection
connection = Connection('localhost', 27017)
db = connection.test
names = db.names
item = names.find_one()
return '<b>Hello %s!</b>' % item['name']
bottle.run(host='localhost', port=8082)
-!-- hello.py All L8 (Python)
I want to run this locally and I go to http://localhost:8082 but I get not found not found. How can I run that code to test it locally on my computer so I can test the code via the browser. I am running Windows 7 and have WAMP installed.
1) Add : after function name:
def index():
2) WAMP does not include MongoDB. You need to install Mongodb locally as well.
3) If something doesn't work, then you generally should be looking console for errors.
This script will run standalone (bottle.run() starts its own Python webserver), so you do not need any WAMP - just run this script. Run it from command line so you see if there are any errors.
You also need to have running MongoDB to connect to it. You can run it from command line too if you do not have MongoDB configured to start automatically after Windows start.

Categories

Resources