How to connect i18n to flask application? - python

I want to make my API to support multiple languages, so it can get the lang header and respond in the same language, but I struggle when it comes part to implement this i18n.
Here's my folder structure in the left, and the translations:
My translations are in JSON format and located in /lang folder.
Here's my app.py:
# Load env
from dotenv import load_dotenv
load_dotenv()
import i18n
i18n.set('file_format', 'json')
i18n.load_path.append('/lang')
# Import init_credentials
from credentials.init_credentials import *
from flask import Flask
from flask_restful import Api
#Imports for the API
from src.Root.rootPoint import Root
#etc..
https://github.com/danhper/python-i18n#readme
It does not work when I try to use the approach from documentation.
i18n.t('phoneAlreadyLinked') #phoneAlreadyLinked

Related

How to remove older css files after webassets rebuilds the scss for a python flask app?

I have a Python 3.9 flask app which uses the flask_assets library.
My flask init.py file looks like:
import logging
import os
from flask import Flask, request, current_app
from config import Config
from flask_assets import Environment
from app.utils.assets import bundles
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(config_class)
assets = Environment(app)
assets.debug = True
assets.versions = 'timestamp'
# assets.cache = False
from app.main import bp as main_bp
app.register_blueprint(main_bp)
assets.register(bundles)
if not app.debug and not app.testing:
app.logger.setLevel(logging.INFO)
app.logger.info('Application starting.')
return app
Since flask_assets is built on top of webassets, I import the Environment and a css Bundle I created which compiles my scss code to css.
Here is how my Bundle looks like:
from flask_assets import Bundle
bundles = {
'css': Bundle (
'scss/_main.scss',
'scss/_base.scss',
'scss/_typography.scss',
'scss/_page_home.scss',
'scss/_page_technote.scss',
filters='pyscss',
depends=('**/*.scss'),
output='css/style.%(version)s.scss.css'
)
}
The problem I have:
Every time I make a change to my scss files, the css successfully rebuilds with a new version for cache busting. However, the older css files remain.
What's the best automatic way to remove them every time a rebuild happens? Is there any reason for keeping the older files?
Also - side question - is it possible for the Bundle object to automatically consider all files of certain type in a directory? Rather than me listing every file individually?
Here is how my files look like:
Thank you!
You can use rmtree. Even though I believe a better way exists, this does it.
from os.path import join
from shutil import rmtree
app = Flask(__name__)
rmtree(join(app.static_folder, 'css'), ignore_errors=True)
You can improve this by checking the file meta by date or similar to not delete the unchanged ones.

How to stop Atom automatically putting imports to the top in python

I have this code in atom;
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config["SECRET_KEY"] = "D02C6E9F82CB9F4D"
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///site.db"
db = SQLAlchemy(app)
from flaskSite import routes
When I save this in atom it puts the from flaskSite import routes to the top but I need at the bottom.
Why does it do this?
These are the packages installed to atom;
atom-live-server
autoclave-html
autocomplete-python
emmet
file-icons
kite
script
python-autopep8
Thank you
It's for sure the autopep feature, got the same problem and have to disable that package each time I don't want to rearrange the imports.

os.getenv() is not pulling a variable I previously declare

I'm new to python and I cannot seem to figure out why I cannot get the os.getenv() function to work. It keeps returning None which is the default value if something is not there. Here is my code:
import os
import datetime
import plaid
from flask import Flask
from flask import render_template
from flask import request
from flask import jsonify
app = Flask(__name__)
PLAID_CLIENT_ID='entercharhere'
PLAID_ENV='sandbox'
#edit here
os.environ['PLAID_CLIENT_ID']='entercharhere'
os.environ['PLAID_ENV']='sandbox'
print(PLAID_CLIENT_ID)
# Fill in your Plaid API keys - https://dashboard.plaid.com/account/keys
PLAID_CLIENT_ID = os.getenv('PLAID_CLIENT_ID')
# Use 'sandbox' to test with Plaid's Sandbox environment (username: user_good,
# password: pass_good)
# Use `development` to test with live users and credentials and `production`
# to go live
PLAID_ENV = os.getenv('PLAID_ENV','sandbox')
print(PLAID_CLIENT_ID)
The output I am receiving is entercharhere and None
EDIT
I wound up switching my declaration of variables to send them to the environment using this:
os.environ['PLAID_CLIENT_ID']='entercharhere'
os.environ['PLAID_ENV']='sandbox'
Is this the best way to do it?
Works perfectly:
import os
os.environ['SOMEVAR'] = 'bla'
print(os.getenv('SOMEVAR'))
# in your shell: export SOMEVAR1="blabla"
print(os.getenv('SOMEVAR1'))
Gives:
bla
blabla

GAE Webapp: the cost of importing a bunch of request handlers

My python GAE app's central application file looks like this:
import webapp2
import homepage
import user_auth
import user_confirm
import admin_user
import admin_config
import config
app = webapp2.WSGIApplication([
(user_auth.get_login_url(), user_auth.LoginHandler),
(user_auth.get_logout_url(), user_auth.LogoutHandler),
("/user/confirm", user_confirm.UserConfirmHandler),
("/admin/config", admin_config.AdminConfigHandler),
("/admin/user/add", admin_user.AdminAddUserHandler),
("/admin/user", admin_user.AdminUserHandler),
("/", homepage.HomepageHandler),
], debug=True)
As you can see, I must import a bunch of request handlers, but for each request, only one of them is used, the other imports are just useless!
That's a big waste of memory and performance because those unnecessary imports also import other things on their own. Does Google App Engine have some "caching" mechanism or something that makes these unnecessary imports negligible? I think not.
How can I avoid them? I just haven't found out the way to import 1 Request Handler per request. If I put all the routing to app.yaml, that would work the way I want, but it makes things complex because I must write app = webapp2.WSGIApplication(... for every request handler file and repeat those boring urls twice (both in the python file and in app.yaml).
Found the way here, already built into webapp2
http://webapp-improved.appspot.com/guide/routing.html#lazy-handlers

Cant fetch production db results using Google app engine remote_api

Hey, I'm trying to work out with /remote_api with a django-patch app engine app i got running.
i want to select a few rows from my online production app locally.
i cant seem to manage to do so, everything authenticates fine, it doesnt breaks on imports, but when i try to fetch something it just doesnt print anything.
Placed the test python inside my local app dir.
#!/usr/bin/env python
#
import os
import sys
# Hardwire in appengine modules to PYTHONPATH
# or use wrapper to do it more elegantly
appengine_dirs = ['myworkingpath']
sys.path.extend(appengine_dirs)
# Add your models to path
my_root_dir = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, my_root_dir)
from google.appengine.ext import db
from google.appengine.ext.remote_api import remote_api_stub
import getpass
APP_NAME = 'Myappname'
os.environ['AUTH_DOMAIN'] = 'gmail.com'
os.environ['USER_EMAIL'] = 'myuser#gmail.com'
def auth_func():
return (raw_input('Username:'), getpass.getpass('Password:'))
# Use local dev server by passing in as parameter:
# servername='localhost:8080'
# Otherwise, remote_api assumes you are targeting APP_NAME.appspot.com
remote_api_stub.ConfigureRemoteDatastore(APP_NAME,
'/remote_api', auth_func)
# Do stuff like your code was running on App Engine
from channel.models import Channel, Channel2Operator
myresults = mymodel.all().fetch(10)
for result in myresults:
print result.key()
it doesn't give any error or print anything. so does the remote_api console example google got. when i print the myresults i get [].
App Engine patch monkeypatches the ext.db module, mutilating the kind names. You need to make sure you import App Engine patch from your script, to give it the opportunity to mangle things as per usual, or you won't see any data returned.

Categories