def get_logger(name: str,
               level=logging.INFO,
               exception_style: str = "darkbg2"):
    stackprinter.set_excepthook(style=exception_style)
    ''' this func has exactly the same result as the code above'''

    structlog.configure(
        processors=[
            structlog.stdlib.add_logger_name,
            structlog.stdlib.add_log_level,
            structlog.stdlib.PositionalArgumentsFormatter(),
            structlog.processors.TimeStamper(fmt="%Y-%m-%d %H:%M.%S"),
            structlog.processors.StackInfoRenderer(),
            # structlog.processors.ExceptionPrettyPrinter(),
            structlog.processors.format_exc_info,
            structlog.dev.ConsoleRenderer()  # <===
        ],
        context_class=dict,
        logger_factory=structlog.stdlib.LoggerFactory(),
        wrapper_class=structlog.stdlib.BoundLogger,
        cache_logger_on_first_use=True,
    )

    logging.basicConfig(
        format="%(message)s\n\r:%(filename)s:%(funcName)s:line%(lineno)s",
        stream=sys.stdout,
        level=level,
    )

    root_logger = structlog.get_logger(name)
    return root_logger
Example #2
0
def get_blogger(name: str,
                level=logging.INFO,
                exception_style: str = "darkbg2"):
    stackprinter.set_excepthook(style=exception_style)
    ''' this func has exactly the same result as the code above'''

    structlog.configure(
        processors=[
            structlog.stdlib.add_logger_name,
            structlog.stdlib.add_log_level,
            structlog.stdlib.PositionalArgumentsFormatter(),
            structlog.processors.TimeStamper(fmt="%Y-%m-%d %H:%M.%S"),
            structlog.processors.StackInfoRenderer(),
            # structlog.processors.ExceptionPrettyPrinter(),
            # SentryProcessor(level=logging.ERROR),
            structlog.processors.format_exc_info,
            structlog.dev.ConsoleRenderer()  # <===
        ],
        context_class=dict,
        logger_factory=structlog.stdlib.LoggerFactory(),
        wrapper_class=structlog.stdlib.BoundLogger,
        cache_logger_on_first_use=True,
    )

    # formatter = structlog.stdlib.ProcessorFormatter(
    #     processor=structlog.dev.ConsoleRenderer(),
    # )

    logging.basicConfig(
        format=
        "%(message)s\n\r\033[2m---%(filename)s:%(funcName)s:line%(lineno)s\033[0m",
        stream=sys.stdout,
        level=level,
    )

    # handler = logging.StreamHandler()
    # handler.setFormatter(formatter)
    # root_logger = logging.getLogger()
    # root_logger.addHandler(handler)
    # root_logger.setLevel(logging.INFO)

    root_logger = structlog.get_logger(name)

    # loop = asyncio.get_event_loop()
    # loop.run_until_complete(get_connection(logger=root_logger))

    return root_logger
Example #3
0
def prettify_stacktrace():
    import pretty_errors
    import stackprinter
    stackprinter.set_excepthook(style='lightbg2')

    pretty_errors.configure(separator_character='*',
                            filename_display=pretty_errors.FILENAME_EXTENDED,
                            line_number_first=True,
                            display_link=True,
                            lines_before=5,
                            lines_after=2,
                            line_color=pretty_errors.RED + '> ' +
                            pretty_errors.default_config.line_color,
                            code_color='  ' +
                            pretty_errors.default_config.line_color,
                            truncate_code=True,
                            display_locals=True)
    pretty_errors.blacklist('c:/python')
    pretty_errors.replace_stderr()
    print(f"Enabled: pretty_errors & stackprinter")
Example #4
0
def test_suite():
    logging.basicConfig(level=logging.DEBUG)
    stackprinter.set_excepthook(style="darkbg")
    test_loader = unittest.TestLoader()
    suite = test_loader.discover(start_dir="tests", top_level_dir=".")
    return suite
Example #5
0
#     21
# --> 22   process_words(words)
#     ..................................................
#      words = ['debugging', 'with', 'stackprinter', 42, ]
#     ..................................................

# File debug_with_stackprinter.py, line 20, in process_words
#     18   def process_words(words_to_process):
#     19       for i, word in enumerate(words_to_process):
# --> 20           processed_word = str.capitalize(word)
#     ..................................................
#      words_to_process = ['debugging', 'with', 'stackprinter', 42, ]
#      i = 3
#      word = 42
#      processed_word = 'Stackprinter'
#     ..................................................

# TypeError: descriptor 'capitalize' requires a 'str' object but received a 'int'

import stackprinter
stackprinter.set_excepthook(style='darkbg2')

words = ['debugging', 'with', 'stackprinter', 42]


def process_words(words_to_process):
    for i, word in enumerate(words_to_process):
        processed_word = str.capitalize(word)


process_words(words)
Example #6
0
# pylint: skip-file
"""
Contains configurations and settings used by the rest of the project.

Any settings in here can be overriden by config_private.py.
"""
import functools
import getpass
import os
import pathlib
from typing import Any, Callable

import stackprinter

stackprinter.set_excepthook(style="darkbg")  # easier to read stack traces

_PROJECT_DIR = pathlib.Path(__file__).resolve().parent.parent

DATA_DIR = _PROJECT_DIR / "data"
RESOURCE_DIR = _PROJECT_DIR / "resources"

# CAS Authentication
#
# When off campus and not connected to the Yale VPN, you must use cookie-based authentication.
# The credentials are only used if CAS_USE_COOKIE is set to False, and the cookie data is
# only used when CAS_USE_COOKIE is set to True.
#
# The latter three settings can also be set to a function. The function should return the
# specified setting when called.
CAS_USE_COOKIE = True
CAS_CREDENTIAL_NETID: Callable[[Any], str] = functools.lru_cache(
Example #7
0
#------------------------------------------------------------------------------
# StoreMagics(Magics) configuration
#------------------------------------------------------------------------------

## Lightweight persistence for python variables.
#
#  Provides the %store magic.

## If True, any %store-d variables will be automatically restored when IPython
#  starts.
#c.StoreMagics.autorestore = False

import os
import numpy as np
from sympy import *
x, y, z, t = symbols('x y z t')
k, m, n = symbols('k m n', integer=True)
f, g, h = symbols('f g h', cls=Function)
init_printing()


def import_all(modules):
    """ Usage: import_all("os sys") """
    for m in modules.split():
        ip.ex("from %s import *" % m)


import stackprinter
stackprinter.set_excepthook(style='color')
Example #8
0
def load_ipython_extension(_: InteractiveShell) -> None:
    """Load stackprinter."""
    import stackprinter

    stackprinter.set_excepthook(style="darkbg2")
Example #9
0
# Standard Library
import sys

try:
    import stackprinter
except ImportError:
    pass
else:
    if sys.stdout.isatty():
        _style = "darkbg2"
    else:
        _style = "plaintext"
    stackprinter.set_excepthook(style=_style)
Example #10
0
import stackprinter

from . import (DEFAULT_API_RETRIES, DEFAULT_API_TIMEOUT,
               DEFAULT_RETRY_BACKOFF_FACTOR, GREEN, NL, RED, WHITE, YELLOW,
               BasicAuthConfiguration, Configuration, Logger, artemis_create,
               artemis_delete, artemis_get_console_url, artemis_inspect,
               artemis_restore, artemis_update, confirm, fetch_artemis,
               load_yaml, prettify_json, prettify_yaml, print_table, prompt,
               validate_struct)

# to prevent infinite loop in pagination support
PAGINATION_MAX_COUNT = 10000

stackprinter.set_excepthook(style='darkbg2',
                            source_lines=7,
                            show_signature=True,
                            show_vals='all',
                            reverse=False,
                            add_summary=False)

click_completion.init()

API_FEATURE_VERSIONS = {
    feature: semver.VersionInfo.parse(version)
    for feature, version in (
        ('hw-constraints-boot-method', '0.0.32'),
        ('hw-constraints-network', '0.0.28'),
        # Dummy version - we can't actually check the constraints to assure this. That could change if we could verify
        # the constraints with a schema, and that would mean gain access to Artemis server package...
        ('hw-constraints-disk-as-list', '0.0.27'),
        ('log-types', '0.0.26'),
        ('skip-prepare-verify-ssh', '0.0.24'),
Example #11
0
from functools import partial
from textwrap import TextWrapper
from youtube_dl.hunterconfig import QueryConfig
from IPython.display import display, HTML
from fmtutil.row.classes import (
  SimpleFunkWithArgs, VerboseList,
  ParsedTuple, LineEvent,
  ParsedHTML, ParsedJSON,
  FormatSymbols, MutableStr,
  DataCollections
  )
from dataclasses import dataclass
import stackprinter
import dill as pickle
from enum import Enum
stackprinter.set_excepthook(style='lightbg2')
basepath = Path('/Users/alberthan/VSCodeProjects/vytd')
args_line_idx_len = 76
fmt_syms = FormatSymbols()
trunc_start,trunc_end = 0, 15

@dataclass
class HeaderRow:
  header: Union[str,None]
  row: tuple

  def __iter__(self):
    idr = iter([self.header,self.row])
    yield next(idr)

  def __len__(self):
Example #12
0
import stackprinter

stackprinter.set_excepthook(style="lightbg")
Example #13
0
import urllib, http, optparse
from urllib.parse import urlparse, ParseResult
from validator_collection import validators, checkers
from hunter import CallPrinter
from ipdb import set_trace as st
import sys, shelve, re, codecs
from typing import Iterable
import stackprinter
from prettyprinter import pformat
from bs4 import BeautifulSoup
from pathlib import Path
from textwrap import TextWrapper

stackprinter.set_excepthook(
    style='lightbg2',  #'darkbg3',
    source_lines=5,
    show_signature=True,
    show_vals='like_source',
    truncate_vals=500)


def info(o):
    try:
        lng = len(o)
    except TypeError as exc:
        lng = "cannot len this obj"
    typ = type(o)
    s = f"\n\n{typ}, {lng}\n{repr(o)}\n\n"
    return s


def auto_repr(obj):
Example #14
0
def get_structlogger(name: str, exception_style: str = "darkbg2"):
    stackprinter.set_excepthook(style=exception_style)
    root_logger = structlog.getLogger(name)
    return root_logger
Example #15
0
def get_logger(name: str,
               level=logging.INFO,
               exception_style: str = "darkbg2"):
    stackprinter.set_excepthook(style=exception_style)
    root_logger = logging.getLogger(name)
    return root_logger
Example #16
0
    def download(self, sessionId):
        url = f"https://pangpang.dooray.com/v2/wapi/projects/*/posts?order=-createdAt&page=0&projectScope=all&size=30&toMemberIds=2006398569098578504&userWorkflowClass=registered,working"
        count, contents = self.fetchPost(url, sessionId)
        self.toExcel("2.第二重境/temp_data", contents)

    def fetchPost(self, url, sessionId):
        cookies_jar = requests.cookies.RequestsCookieJar()
        cookies_jar.set('SESSION', sessionId, domain='.dooray.com', path='/')
        resp = requests.get(url, cookies=cookies_jar)
        post = resp.json()
        totalCount = post["result"]["totalCount"]
        contents = post["result"]["contents"]
        return totalCount, contents

    def toExcel(self, abPath, contents):
        fileName = "dooray_post.xlsx"
        excelPath = "{}/{}".format(abPath, fileName)
        dataframe = pandas.DataFrame(contents)
        dataframe.to_excel(excelPath, encoding="utf-8")
        return None


if __name__ == "__main__":
    stackprinter.set_excepthook()
    try:
        sessionId = input("请输入dooray的sessionId:")
        m = DorDownloader()
        m.download(sessionId)
    except Exception as inst:
        stackprinter.show(style='plaintext', source_lines=4)
import asyncio
from decimal import Decimal

import httpx
import stackprinter #type: ignore
stackprinter.set_excepthook(style="darkbg2")


# noobit base
from noobit_markets.base.models.rest.response import NSymbol, NSingleOrder
from noobit_markets.base import ntypes

# noobit binance public
from noobit_markets.exchanges.binance.rest.public.symbols import get_symbols_binance
from noobit_markets.exchanges.binance.rest.private.balances import get_balances_binance

# noobit binance private
from noobit_markets.exchanges.binance.rest.private.orders import (
    get_closedorders_binance,
)
from noobit_markets.exchanges.binance.rest.private.trades import get_trades_binance
from noobit_markets.exchanges.binance.rest.private.trading import post_neworder_binance

from noobit_markets.exchanges.binance.rest.private.exposure import get_exposure_binance
from noobit_markets.exchanges.binance.rest.private.ws_auth import get_wstoken_binance



# ============================================================
# SYMBOLS
# ============================================================
Example #18
0
from smart_getenv import getenv
from dotenv import load_dotenv

load_dotenv()

if not getenv("IS_PROD", type=bool):
    import stackprinter

    stackprinter.set_excepthook(style="color")