def _get_full_hostname(self): if self.request.app.prod_mode: return 'www.dancedeets.com' elif os.environ.get('HOT_SERVER_PORT'): host_port = app_identity.get_default_version_hostname() host, port = host_port.split(':') return '%s:%s' % (host, os.environ['HOT_SERVER_PORT']) else: return app_identity.get_default_version_hostname()
def get(self): ### height:421px width:400px ### width will be about 800px # self.response.headers['Content-Type'] = 'image/png' ### put out resized png image which matches Twitter card. ### Basic concept ### 1: Prepare white back png which width is 800px, height is 421px. ### 2: put diagram image center of the images img = '' img_list = [] ### Make white background image (800x421 px) with open('img/whitebase.png', 'rb') as f: img = f.read() img = images.resize(img, self.WIDTH, self.HEIGHT, allow_stretch=True) img_list += [(img, 0, 0, 1.0, images.TOP_LEFT)] url = 'http://' + app_identity.get_default_version_hostname() + '/sfen?' + self.request.query_string diagram_img = urllib2.urlopen(url).read() diagram_img_obj = Image(diagram_img) ### for width, height # x = (self.WIDTH - diagram_img_obj.width) // 2 x = (self.WIDTH - diagram_img_obj.width) // 2 img_list += [(diagram_img, x, 0, 1.0, images.TOP_LEFT)] img = images.composite(img_list, self.WIDTH, self.HEIGHT, color=0xFFFFFFFF) self.response.headers['Content-Type'] = 'image/png' self.response.out.write(img)
def get_app_host(include_version=True): host = app_identity.get_default_version_hostname() server = os.environ.get("SERVER_SOFTWARE", "") version = os.environ.get("CURRENT_VERSION_ID", ".").split(".")[0] if version and include_version and not server.startswith("Dev"): host = "%s-dot-%s" % (version, host) return host
def normalize_dest_url(cls, val): """ Coerces url to standard allowable form, stripping fragment and rejecting certain conditions which are not allowed due to such things as ambiguous destinations or security considerations. Validates/Coerces a proposed url based upon the constraints of model which are: Scheme: If url has not scheme, it is assigned 'http'. Certain scehes are not allowed. In particular, data: and javascript:. Host: references to local machine are not allowed in production mode. Thus the model will disallow 'localhost', '127.0.0.1'. Relative urls (i.e. empty host) are also not allowed. Validation only pertains to logical qualities related to the datamodel. The validation includes checks for neither white space nor valid characters Args: val (str): string representation of a url. string must contain only valid url characters Returns: urlparse.SplitResult Raises: ModelConstraintError if and constraints regarding destination urls are violated """ if len(val) > MAX_URL_LENGTH: raise DestinationUrlError(DestinationUrlError.URL_TOO_LONG, max_len=MAX_URL_LENGTH) original = urlparse.urlsplit(val) if not original.netloc: if val.startswith(original.scheme): raise DestinationUrlError( DestinationUrlError.RELATIVE_URL_NOT_ALLOWED) else: raise DestinationUrlError(DestinationUrlError.HOST_OMITTED) if not original.hostname or original.hostname in LOCALHOSTS: raise DestinationUrlError( DestinationUrlError.LOCALHOST_NOT_ALLOWED) elif -1 != original.hostname.find( app_identity.get_default_version_hostname()): raise DestinationUrlError( DestinationUrlError.RECURSIVE_REDIRECTION_ALLOWED) if original.scheme: if original.scheme not in ALLOWED_SCHEMES: raise DestinationUrlError( DestinationUrlError.SCHEME_NOT_ALLOWED, original.scheme) coerced_scheme = original.scheme if original.scheme else DEFAULT_URL_SCHEME return NormalizedUrl(scheme=coerced_scheme, netloc=original.netloc, path=original.path, query=original.query)
def normalize_dest_url(cls, val): """ Coerces url to standard allowable form, stripping fragment and rejecting certain conditions which are not allowed due to such things as ambiguous destinations or security considerations. Validates/Coerces a proposed url based upon the constraints of model which are: Scheme: If url has not scheme, it is assigned 'http'. Certain scehes are not allowed. In particular, data: and javascript:. Host: references to local machine are not allowed in production mode. Thus the model will disallow 'localhost', '127.0.0.1'. Relative urls (i.e. empty host) are also not allowed. Validation only pertains to logical qualities related to the datamodel. The validation includes checks for neither white space nor valid characters Args: val (str): string representation of a url. string must contain only valid url characters Returns: urlparse.SplitResult Raises: ModelConstraintError if and constraints regarding destination urls are violated """ if len(val) > MAX_URL_LENGTH: raise DestinationUrlError(DestinationUrlError.URL_TOO_LONG, max_len=MAX_URL_LENGTH) original = urlparse.urlsplit(val) if not original.netloc: if val.startswith(original.scheme): raise DestinationUrlError(DestinationUrlError.RELATIVE_URL_NOT_ALLOWED) else: raise DestinationUrlError(DestinationUrlError.HOST_OMITTED) if not original.hostname or original.hostname in LOCALHOSTS: raise DestinationUrlError(DestinationUrlError.LOCALHOST_NOT_ALLOWED) elif -1 != original.hostname.find(app_identity.get_default_version_hostname()): raise DestinationUrlError(DestinationUrlError.RECURSIVE_REDIRECTION_ALLOWED) if original.scheme: if original.scheme not in ALLOWED_SCHEMES: raise DestinationUrlError(DestinationUrlError.SCHEME_NOT_ALLOWED, original.scheme) coerced_scheme = original.scheme if original.scheme else DEFAULT_URL_SCHEME return NormalizedUrl( scheme=coerced_scheme, netloc=original.netloc, path=original.path, query=original.query)
def home_rss(sid): flask.g.host = app_identity.get_default_version_hostname() sid = str(sid) try: sid = crypto.decrypt(base64.urlsafe_b64decode(sid), flask.current_app.config["SECRET_KEY"]) oauth_token, oauth_token_secret = sid.split(":", 1) except (ValueError, TypeError): return "Invalid sid." flask.g.api.bind_auth(oauth_token, oauth_token_secret) params = flask.request.args.to_dict() params["tweet_mode"] = "extended" if "count" not in params: params["count"] = 200 cached = memcache.get(sid + str(params)) if cached: logging.debug("fetched from memcache") data = { "title": "Home", "results": json.loads(zlib.decompress(cached)) } else: data = timeline.timeline( "Home", functools.partial(flask.g.api.get, "statuses/home_timeline", **params)) data["results"].sort(cmp=lambda a, b: int( time.mktime(email.utils.parsedate(a["created_at"])) - time.mktime( email.utils.parsedate(b["created_at"]))), reverse=True) logging.debug("rss result: %d", len(data["results"])) for tweet in data["results"]: new_text = indicesreplace.IndicesReplace(tweet["full_text"]) entities = tweet.get("entities", {}) for url in entities.get("urls", []): start, stop = url["indices"] new_text.replace_indices(start, stop, url["display_url"]) for url in entities.get("media", []): start, stop = url["indices"] new_text.replace_indices(start, stop, url["display_url"]) tweet["rss_title"] = unicode(new_text).replace( "\r\n", " ").replace("\r", " ").replace("\n", " ") memcache.set(sid + str(params), zlib.compress(json.dumps(data["results"]), 9), time=120) data["now"] = email.utils.formatdate() resp = flask.make_response(flask.render_template("rss.xml", **data)) resp.headers["Content-Type"] = "application/rss+xml; charset=utf-8" return resp
def home_rss(sid): flask.g.host = app_identity.get_default_version_hostname() sid = str(sid) try: sid = crypto.decrypt(base64.urlsafe_b64decode(sid), flask.current_app.config["SECRET_KEY"]) oauth_token, oauth_token_secret = sid.split(":", 1) except (ValueError, TypeError): return "Invalid sid." flask.g.api.bind_auth(oauth_token, oauth_token_secret) params = flask.request.args.to_dict() params["tweet_mode"] = "extended" if "count" not in params: params["count"] = 200 cached = memcache.get(sid + str(params)) if cached: logging.debug("fetched from memcache") data = { "title": "Home", "results": json.loads(zlib.decompress(cached)) } else: data = timeline.timeline("Home", functools.partial(flask.g.api.get, "statuses/home_timeline", **params)) data["results"].sort( cmp=lambda a, b: int(time.mktime(email.utils.parsedate(a["created_at"])) - time.mktime( email.utils.parsedate(b["created_at"]))), reverse=True) logging.debug("rss result: %d", len(data["results"])) for tweet in data["results"]: new_text = indicesreplace.IndicesReplace(tweet["full_text"]) entities = tweet.get("entities", {}) for url in entities.get("urls", []): start, stop = url["indices"] new_text.replace_indices(start, stop, url["display_url"]) for url in entities.get("media", []): start, stop = url["indices"] new_text.replace_indices(start, stop, url["display_url"]) tweet["rss_title"] = unicode(new_text).replace("\r\n", " ").replace("\r", " ").replace("\n", " ") memcache.set(sid + str(params), zlib.compress(json.dumps(data["results"]), 9), time=120) data["now"] = email.utils.formatdate() resp = flask.make_response(flask.render_template("rss.xml", **data)) resp.headers["Content-Type"] = "application/rss+xml; charset=utf-8" return resp
def _get_full_hostname(self): return 'www.dancedeets.com' if self.request.app.prod_mode else app_identity.get_default_version_hostname()
def _get_full_hostname(self): return 'www.dancedeets.com' if self.request.app.prod_mode else app_identity.get_default_version_hostname( )
# # Copyright 2015 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os from google.appengine.api.app_identity.app_identity import get_default_version_hostname RUNNER_ENDPOINT = '/runner' RESULT_KEYNAME = 'RESULT' SERVER_SOFTWARE = os.environ.get('SERVER_SOFTWARE') IS_PRODUCTION = SERVER_SOFTWARE.startswith('Google') DEFAULT_VERSION_HOSTNAME = get_default_version_hostname() HOST = 'hackaton-1009.appspot.com' if IS_PRODUCTION else 'localhost:8080'
from google.appengine.api.app_identity import app_identity from gaecookie.middleware import CSRFMiddleware, CSRFInputToDependency from locale_app.middleware import LocaleMiddleware from multitenancy import MultitenacyMiddleware, set_subdomain, set_domain from tekton.gae.middleware.json_middleware import JsonResponseMiddleware from config.template_middleware import TemplateMiddleware, TemplateWriteMiddleware from tekton.gae.middleware.email_errors import EmailMiddleware from tekton.gae.middleware.parameter import RequestParamsMiddleware from tekton.gae.middleware.redirect import RedirectMiddleware from tekton.gae.middleware.router_middleware import RouterMiddleware, ExecutionMiddleware from tekton.gae.middleware.webapp2_dependencies import Webapp2Dependencies from gaepermission.middleware import LoggedUserMiddleware, PermissionMiddleware APP_NAME = 'Passwordless' APP_HOST = app_identity.get_default_version_hostname() or r'pswdless.appspot.com' APP_HOME = 'http://' + APP_HOST if APP_HOST.startswith('localhost') else 'https://' + APP_HOST # See queue.yaml for configuration TASK_HERO = 'hero' LINK_EXPIRATION = 1800 # link must be used on 1800 seconds (30 minutes) APP_URL = APP_HOME SENDER_EMAIL = 'Passwordless<*****@*****.**>' DEFAULT_LOCALE = 'en_US' DEFAULT_TIMEZONE = 'US/Eastern' LOCALES = ['en_US', 'pt_BR'] TEMPLATE_404_ERROR = 'base/404.html' TEMPLATE_400_ERROR = 'base/400.html'
def _create_service(): url = 'https://{}/tbans/tbans'.format(app_identity.get_default_version_hostname()) return TBANSService.Stub(transport.HttpTransport(url))
def host_url(): hostname = app_identity.get_default_version_hostname() return urlparse.urlunsplit(('http', hostname, '', '', ''))