Python config.USERNAME Examples
The following are 18
code examples of config.USERNAME().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
config
, or try the search function
.
Example #1
Source File: main.py From sneakpeek with MIT License | 6 votes |
def start(): """Start the sneakpeek application.""" logging.info("Starting application") logging.info("Instantiating Reddit instance") reddit = praw.Reddit( client_id=config.CLIENT["ID"], client_secret=config.CLIENT["SECRET"], user_agent=config.USER_AGENT, username=config.USERNAME, password=config.PASSWORD) try: scan(reddit.subreddit(config.SUBREDDIT)) except Exception as exception: # This should never happen, # because it breaks the infinite subreddit monitoring # provided by subreddit.stream.submissions() logging.critical("Exception occurred while scanning. This should never happen.") logging.critical(exception)
Example #2
Source File: models.py From stack with MIT License | 6 votes |
def __init__(self, local=True): if local: # Class instance connection to Mongo self.connection = MongoClient() if config.AUTH: try: self.connection.admin.authenticate(config.USERNAME, config.PASSWORD) except: print('Error: Authentication failed. Please check:\n1. MongoDB credentials in config.py\n2. MongoDB uses the correct authentication schema (MONGODB-CR)\nFor more info. see https://github.com/bitslabsyr/stack/wiki/Installation') sys.exit(1) # App-wide config file for project info access self.config_db = self.connection.config self.stack_config = self.config_db.config else: self.connection = MongoClient(config.CT_SERVER) if config.CT_AUTH: try: self.connection.admin.authenticate(config.CT_USERNAME, config.CT_PASSWORD) except: print('Error: Authentication failed at the central server. Please check:\n1. MongoDB credentials in config.py\n2. MongoDB uses the correct authentication schema (MONGODB-CR)\nFor more info. see https://github.com/bitslabsyr/stack/wiki/Installation') sys.exit(1)
Example #3
Source File: credentials.py From OpenBazaar-Server with MIT License | 6 votes |
def get_credentials(database): settings = database.settings creds = settings.get_credentials() if creds == (USERNAME, PASSWORD): return creds elif creds is not None and (USERNAME is None or PASSWORD is None): return creds elif creds is not None and USERNAME is not None and PASSWORD is not None: settings.set_credentials(USERNAME, PASSWORD) return (USERNAME, PASSWORD) elif creds is None and (USERNAME is None or PASSWORD is None): username = base64.b64encode(sha256(str(random.getrandbits(255))).digest())[:20] password = base64.b64encode(sha256(str(random.getrandbits(255))).digest())[:20] settings.set_credentials(username, password) return (username, password) elif creds is None and (USERNAME is not None and PASSWORD is not None): settings.set_credentials(USERNAME, PASSWORD) return (USERNAME, PASSWORD)
Example #4
Source File: worker.py From DotaResponsesRedditBot with MIT License | 6 votes |
def work(): """Main method executing the script. It connects to an account, loads dictionaries from proper files (declared in config file). Afterwards it executes process_comments method with proper arguments passed. """ reddit = account.get_account() logger.info('Connected to Reddit account : ' + config.USERNAME) comment_stream = reddit.subreddit(config.SUBREDDIT).stream.comments(pause_after=-1) submission_stream = reddit.subreddit(config.SUBREDDIT).stream.submissions(pause_after=-1) while True: for comment in comment_stream: if comment is None: break process_replyable(reddit, comment) for submission in submission_stream: if submission is None: break process_replyable(reddit, submission)
Example #5
Source File: demo.py From ringcentral-python with MIT License | 6 votes |
def main(): sdk = SDK(APP_KEY, APP_SECRET, SERVER) platform = sdk.platform() platform.login(USERNAME, EXTENSION, PASSWORD) # Simple GET response = platform.get('/account/~/extension/~') user = response.json() user_id = str(user.id) print('User loaded ' + user.name + ' (' + user_id + ')') print('Headers ' + str(response.response().headers)) print(type(response.response()._content)) # Multipart response try: multipart_response = platform.get('/account/~/extension/' + user_id + ',' + user_id + '/presence').multipart() print('Multipart 1\n' + str(multipart_response[0].json_dict())) print('Multipart 2\n' + str(multipart_response[1].json_dict())) except ApiException as e: print('Cannot load multipart') print('URL ' + e.api_response().request().url) print('Response' + str(e.api_response().json()))
Example #6
Source File: demo_cache.py From ringcentral-python with MIT License | 6 votes |
def main(): cache = get_file_cache() # Create SDK instance sdk = SDK(APP_KEY, APP_SECRET, SERVER) platform = sdk.platform() # Set cached authentication data platform.auth().set_data(cache) try: platform.is_authorized() print('Authorized already by cached data') except Exception as e: platform.login(USERNAME, EXTENSION, PASSWORD) print('Authorized by credentials') # Perform refresh by force platform.refresh() print('Refreshed') set_file_cache(platform.auth().data()) print("Authentication data has been cached")
Example #7
Source File: feed.py From microblog.pub with GNU Affero General Public License v3.0 | 6 votes |
def gen_feed(): fg = FeedGenerator() fg.id(f"{ID}") fg.title(f"{USERNAME} notes") fg.author({"name": USERNAME}) fg.link(href=ID, rel="alternate") fg.description(f"{USERNAME} notes") fg.logo(ME.get("icon", {}).get("url")) fg.language("en") for item in DB.activities.find( { "box": Box.OUTBOX.value, "type": "Create", "meta.deleted": False, "meta.public": True, }, limit=10, ).sort("_id", -1): fe = fg.add_entry() fe.id(item["activity"]["object"].get("url")) fe.link(href=item["activity"]["object"].get("url")) fe.title(item["activity"]["object"]["content"]) fe.description(item["activity"]["object"]["content"]) return fg
Example #8
Source File: account.py From DotaResponsesRedditBot with MIT License | 5 votes |
def get_account(): """Method that provides the connection to Reddit API using OAuth. :return: Reddit instance. """ return praw.Reddit(client_id=config.CLIENT_ID, client_secret=config.CLIENT_SECRET, user_agent=config.USER_AGENT, username=config.USERNAME, password=config.PASSWORD)
Example #9
Source File: test_bot.py From DotaResponsesRedditBot with MIT License | 5 votes |
def test_account(self): """Method used to test the Reddit instance returned by get_account() """ reddit = account.get_account() self.assertEqual(reddit.user.me(), config.USERNAME)
Example #10
Source File: feed.py From microblog.pub with GNU Affero General Public License v3.0 | 5 votes |
def json_feed(path: str) -> Dict[str, Any]: """JSON Feed (https://jsonfeed.org/) document.""" data = [] for item in DB.activities.find( { "box": Box.OUTBOX.value, "type": "Create", "meta.deleted": False, "meta.public": True, }, limit=10, ).sort("_id", -1): data.append( { "id": item["activity"]["id"], "url": item["activity"]["object"].get("url"), "content_html": item["activity"]["object"]["content"], "content_text": html2text(item["activity"]["object"]["content"]), "date_published": item["activity"]["object"].get("published"), } ) return { "version": "https://jsonfeed.org/version/1", "user_comment": ( "This is a microblog feed. You can add this to your feed reader using the following URL: " + ID + path ), "title": USERNAME, "home_page_url": ID, "feed_url": ID + path, "author": { "name": USERNAME, "url": ID, "avatar": ME.get("icon", {}).get("url"), }, "items": data, }
Example #11
Source File: well_known.py From microblog.pub with GNU Affero General Public License v3.0 | 5 votes |
def nodeinfo() -> Any: """NodeInfo endpoint.""" q = { "box": Box.OUTBOX.value, "meta.deleted": False, "type": {"$in": [ap.ActivityType.CREATE.value, ap.ActivityType.ANNOUNCE.value]}, } out = { "version": "2.1", "software": { "name": "microblogpub", "version": config.VERSION, "repository": "https://github.com/tsileo/microblog.pub", }, "protocols": ["activitypub"], "services": {"inbound": [], "outbound": []}, "openRegistrations": False, "usage": {"users": {"total": 1}, "localPosts": DB.activities.count(q)}, "metadata": { "nodeName": f"@{config.USERNAME}@{config.DOMAIN}", "version": config.VERSION, "versionDate": config.VERSION_DATE, }, } return jsonify( out, "application/json; profile=http://nodeinfo.diaspora.software/ns/schema/2.1#", )
Example #12
Source File: well_known.py From microblog.pub with GNU Affero General Public License v3.0 | 5 votes |
def wellknown_webfinger() -> Any: """Exposes/servers WebFinger data.""" resource = request.args.get("resource") if resource not in [f"acct:{config.USERNAME}@{config.DOMAIN}", config.ID]: abort(404) out = { "subject": f"acct:{config.USERNAME}@{config.DOMAIN}", "aliases": [config.ID], "links": [ { "rel": "http://webfinger.net/rel/profile-page", "type": "text/html", "href": config.ID, }, {"rel": "self", "type": "application/activity+json", "href": config.ID}, { "rel": "http://ostatus.org/schema/1.0/subscribe", "template": config.BASE_URL + "/authorize_follow?profile={uri}", }, {"rel": "magic-public-key", "href": config.KEY.to_magic_key()}, { "href": config.ICON_URL, "rel": "http://webfinger.net/rel/avatar", "type": mimetypes.guess_type(config.ICON_URL)[0], }, ], } return jsonify(out, "application/jrd+json; charset=utf-8")
Example #13
Source File: demo_mms.py From ringcentral-python with MIT License | 5 votes |
def main(): sdk = SDK(APP_KEY, APP_SECRET, SERVER) platform = sdk.platform() platform.login(USERNAME, EXTENSION, PASSWORD) # Step 1. Get MMS-enabled phone number phone_numbers = platform.get('/account/~/extension/~/phone-number', {'perPage': 'max'}).json().records mms_number = None for phone_number in phone_numbers: if 'MmsSender' in phone_number.features: mms_number = phone_number.phoneNumber print 'MMS Phone Number: ' + mms_number # Step 2. Send MMS attachment = ( 'test.png', urllib.urlopen('https://developers.ringcentral.com/assets/images/ico_case_crm.png').read(), 'image/png' ) builder = sdk.create_multipart_builder() builder.set_body({ 'from': {'phoneNumber': mms_number}, 'to': [{'phoneNumber': MOBILE}], 'text': 'MMS from Python' # this is optional }) builder.add(attachment) request = builder.request('/account/~/extension/~/sms') response = platform.send_request(request) print 'Sent MMS: ' + response.json().uri
Example #14
Source File: demo_sms.py From ringcentral-python with MIT License | 5 votes |
def main(): sdk = SDK(APP_KEY, APP_SECRET, SERVER) platform = sdk.platform() platform.login(USERNAME, EXTENSION, PASSWORD) to_numbers = "1234567890" params = {'from': {'phoneNumber': USERNAME},'to': [{'phoneNumber': to_number}],'text': "SMS message"} response = platform.post('/restapi/v1.0/account/~/extension/~/sms', params) print 'Sent SMS: ' + response.json().uri
Example #15
Source File: demo_subscription.py From ringcentral-python with MIT License | 5 votes |
def main(): sdk = SDK(APP_KEY, APP_SECRET, SERVER) platform = sdk.platform() platform.login(USERNAME, EXTENSION, PASSWORD) def on_message(msg): print(msg) def pubnub(): try: s = sdk.create_subscription() s.add_events(['/account/~/extension/~/message-store']) s.on(Events.notification, on_message) s.register() while True: sleep(0.1) except KeyboardInterrupt: print("Pubnub listener stopped...") p = Process(target=pubnub) try: p.start() except KeyboardInterrupt: p.terminate() print("Stopped by User") print("Wait for notification...")
Example #16
Source File: TestDailymotion.py From dailymotion-sdk-python with MIT License | 5 votes |
def setUpClass(self): self.api_base_url = config.BASE_URL or 'http://api.dailymotion.com' self.api_key = config.CLIENT_ID self.api_secret = config.CLIENT_SECRET self.username = config.USERNAME self.password = config.PASSWORD self.scope = ['manage_videos', 'manage_playlists', 'userinfo'] self.redirect_uri = config.REDIRECT_URI self.oauth_authorize_endpoint_url = config.OAUTH_AUTHORIZE_URL or 'https://api.dailymotion.com/oauth/authorize' self.oauth_token_endpoint_url = config.OAUTH_TOKEN_URL or 'https://api.dailymotion.com/oauth/token' self.session_file_directory = './data' if not os.path.exists(self.session_file_directory): os.makedirs(self.session_file_directory)
Example #17
Source File: shell.py From RobinhoodShell with MIT License | 4 votes |
def __init__(self): cmd.Cmd.__init__(self) self.trader = Robinhood() # Robinhood now uses 2FA # The workflow we use is as follows # If we find auth token in auth.data - try to see if it still works # If yes, continue # If no, try to refresh the token using refresh token # If it still fails, we need to relogin with 2FA try: data = open(self.auth_file).read() auth_data = json.loads(data) if 'auth_token' in auth_data: self.trader.device_token = auth_data['device_token'] self.trader.auth_token = auth_data['auth_token'] self.trader.refresh_token = auth_data['refresh_token'] self.trader.headers['Authorization'] = 'Bearer ' + self.trader.auth_token try: self.trader.user() except: del self.trader.headers['Authorization'] self.trader.relogin_oauth2() self._save_auth_data() except: challenge_type = 'email' if CHALLENGE_TYPE == 'sms': challenge_type = 'sms' self.trader.login(username = USERNAME, password = PASSWORD, challenge_type = challenge_type) self._save_auth_data() try: data = open(self.instruments_cache_file).read() self.instruments_cache = json.loads(data) for k in self.instruments_cache: self.instruments_reverse_cache[self.instruments_cache[k]] = k except: pass try: data = open(self.watchlist_file).read() self.watchlist = json.loads(data) except: pass # nytime = parser.parse('2018-06-15T23:14:15Z').astimezone(to_zone) # from dateutil import parser # ----- basic commands -----
Example #18
Source File: feed.py From microblog.pub with GNU Affero General Public License v3.0 | 4 votes |
def build_inbox_json_feed( path: str, request_cursor: Optional[str] = None ) -> Dict[str, Any]: """Build a JSON feed from the inbox activities.""" data = [] cursor = None q: Dict[str, Any] = { "type": "Create", "meta.deleted": False, "box": Box.INBOX.value, } if request_cursor: q["_id"] = {"$lt": request_cursor} for item in DB.activities.find(q, limit=50).sort("_id", -1): actor = ap.get_backend().fetch_iri(item["activity"]["actor"]) data.append( { "id": item["activity"]["id"], "url": item["activity"]["object"].get("url"), "content_html": item["activity"]["object"]["content"], "content_text": html2text(item["activity"]["object"]["content"]), "date_published": item["activity"]["object"].get("published"), "author": { "name": actor.get("name", actor.get("preferredUsername")), "url": actor.get("url"), "avatar": actor.get("icon", {}).get("url"), }, } ) cursor = str(item["_id"]) resp = { "version": "https://jsonfeed.org/version/1", "title": f"{USERNAME}'s stream", "home_page_url": ID, "feed_url": ID + path, "items": data, } if cursor and len(data) == 50: resp["next_url"] = ID + path + "?cursor=" + cursor return resp