tell相关知识
-
Go vs Java No.123Because of my sudden fantasy , i try to tell you guys some technological infos but results in vary rare read counting. Well , this time i try to tell you the difference between Java and Go.I am not caring whether you're reading or not.0、Hello WorldJavapackage main.java; public class HelloWorld { public static void main(String[] args){ System.
-
【Python 1-12】Python手把手教程之——用户输入input函数作者 | 弗拉德 来源 | 弗拉德 函数input() 函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在一个变量中,以方便你使用。 例如,下面的程序让用户输入一些文本,再将这些文本呈现给用户: message = input("Tell me something, and I will repeat it back to you: ") print(message) 函数input()接受一个参数:即要向用户显示的提示或说明,让用户知道该如何做。在这个示例中,用户将看到提示Tell me something, and I will rep
-
garbage collection brief introductionBefore get started, I want to tell you a joke: A few weeks ago, a conceited idiot told others that he was planning to design and implement a new programming language IN HALF A YEAR when he didn’t even understand how the runtime manages the memory! What is the conceited idiot doing now? He is writing the article you are reading. So today, I want to talk about garbage collection. language
-
Python基础之While循环一、摘要本片博文将介绍input()函数和while循环的使用二、input()函数函数input() 让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在一个变量中,以方便你使用。message = input("Tell me something, and I will repeat it back to you: ")print(message)函数input() 接受一个参数:即要向用户显示的提示 或说明,让用户知道该如何做。在这个示例中,Python运行第1行代码时,用户将看到提示Tell me something, and I will repeat it back to you: 程序等待用户输入,并在用户按回车键后继续运行。输入存储在变量message 中,接下来的print(message) 将输入呈现给用户
tell相关课程
tell相关教程
- 6.1 字符串的值 Kotlin 有两种类型的字符串字面值:转义字符串可以有转义字符, 以及原始字符串可以包含换行以及任意文本。以下是转义字符串的一个示例:val s = "Hello, world!\n"转义采用传统的反斜杠方式。字符串使用三个引号(""")分界符括起来,内部没有转义并且可以包含换行以及任何其他字符:val text = """ for (c in "foo") print(c)"""还可以通过 trimMargin() 函数去除前导空格:val text = """ |Tell me and I forget. |Teach me and I remember. |Involve me and I learn. |(Benjamin Franklin) """.trimMargin()
- 2. 文件对象 open 返回一个 file 对象,通过调用 file 对象的成员方法访问该文件,下表总结了 file 对象的成员方法。成员方法功能close()关闭文件,关闭之后便不能再进行写入write(string)将字符串 string 写入文件read(count)从文件中读取一个字符串,至多读取 count 个字符tell()获取文件的当前访问位置seek(offset, from)改变文件的当前访问位置seek(offset, from) 的功能是根据参数 offset 和 from 改变当前文件的访问位置:参数 offset 表示要移动的字节数参数 from 指定开始移动字节的参考位置如果 from 被设为 0,将文件的开头作为移动的参考位置如果 from 被设为 1,将文件的当前访问位置作为移动的参考位置如果 from 被设为 2,将文件的末尾作为移动的参考位置
- 2.1 json() 方法 带着这两个问题我们来看看 requests 库的源码,可以看到 requests 模块的源码非常少,比较适合阅读。首先看第一个问题,就是要分析下 Response 结果的 json() 方法即可,比较容易找到:# 源码位置:requests/models.py# ...class Response(object): # ... def json(self, **kwargs): r"""Returns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes. :raises ValueError: If the response body does not contain valid json. """ if not self.encoding and self.content and len(self.content) > 3: # No encoding set. JSON RFC 4627 section 3 states we should expect # UTF-8, -16 or -32. Detect which one to use; If the detection or # decoding fails, fall back to `self.text` (using chardet to make # a best guess). encoding = guess_json_utf(self.content) if encoding is not None: try: return complexjson.loads( self.content.decode(encoding), **kwargs ) except UnicodeDecodeError: # Wrong UTF codec detected; usually because it's not UTF-8 # but some other 8-bit codec. This is an RFC violation, # and the server didn't bother to tell us what codec *was* # used. pass return complexjson.loads(self.text, **kwargs) # ...上面的 json() 方法中最核心的只有一句:complexjson.loads(self.content.decode(encoding), **kwargs)而这句和我们前面的得到响应内容,然后使用 json.loads() 是一样的,不过这里使用的是 complexjson。继续看看这个 complexjson 的定义:# 源码位置:requests/models.pyfrom .compat import json as complexjson# 源码位置:requests/compact.pytry: import simplejson as jsonexcept ImportError: import json可以看到,这个 complexjson 其实就是 Python 的第三方 json 模块或者是 Python 的内置 json 模块。因此,对于第一个问题就是显而易见了,使用 r.json() 和我们用 json.loads(r.text) 得到的结果基本是一致的。
- 2.1 Django 中和上传文件相关的基础类 这一节主要是来分析下 Django 中和上传文件相关的代码。首先介绍下几个基础类:FileProxyMixin 类:用于辅助文件上传的 mixin 类。来看看其源码长相:# 源码路径: django/core/files/utils.pyclass FileProxyMixin: """ A mixin class used to forward file methods to an underlaying file object. The internal file object has to be called "file":: class FileProxy(FileProxyMixin): def __init__(self, file): self.file = file """ encoding = property(lambda self: self.file.encoding) fileno = property(lambda self: self.file.fileno) flush = property(lambda self: self.file.flush) isatty = property(lambda self: self.file.isatty) newlines = property(lambda self: self.file.newlines) read = property(lambda self: self.file.read) readinto = property(lambda self: self.file.readinto) readline = property(lambda self: self.file.readline) readlines = property(lambda self: self.file.readlines) seek = property(lambda self: self.file.seek) tell = property(lambda self: self.file.tell) truncate = property(lambda self: self.file.truncate) write = property(lambda self: self.file.write) writelines = property(lambda self: self.file.writelines) @property def closed(self): return not self.file or self.file.closed def readable(self): if self.closed: return False if hasattr(self.file, 'readable'): return self.file.readable() return True def writable(self): if self.closed: return False if hasattr(self.file, 'writable'): return self.file.writable() return 'w' in getattr(self.file, 'mode', '') def seekable(self): if self.closed: return False if hasattr(self.file, 'seekable'): return self.file.seekable() return True def __iter__(self): return iter(self.file)注意:可以看到,想要继承这个 Mixin 并正常使用,继承的类应该有实例属性 file。这里 Mixin 中的属性和我们在 Python 中用 open()方法得到的文件对象的属性几乎一致,后面实验中可以得到佐证。File 类:专门为上传文件的定义的基类,直接看源代码。class File(FileProxyMixin): DEFAULT_CHUNK_SIZE = 64 * 2 ** 10 def __init__(self, file, name=None): self.file = file if name is None: name = getattr(file, 'name', None) self.name = name if hasattr(file, 'mode'): self.mode = file.mode def __str__(self): return self.name or '' def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self or "None") def __bool__(self): return bool(self.name) def __len__(self): return self.size @cached_property def size(self): if hasattr(self.file, 'size'): return self.file.size if hasattr(self.file, 'name'): try: return os.path.getsize(self.file.name) except (OSError, TypeError): pass if hasattr(self.file, 'tell') and hasattr(self.file, 'seek'): pos = self.file.tell() self.file.seek(0, os.SEEK_END) size = self.file.tell() self.file.seek(pos) return size raise AttributeError("Unable to determine the file's size.") def chunks(self, chunk_size=None): """ Read the file and yield chunks of ``chunk_size`` bytes (defaults to ``File.DEFAULT_CHUNK_SIZE``). """ chunk_size = chunk_size or self.DEFAULT_CHUNK_SIZE try: self.seek(0) except (AttributeError, UnsupportedOperation): pass while True: data = self.read(chunk_size) if not data: break yield data def multiple_chunks(self, chunk_size=None): """ Return ``True`` if you can expect multiple chunks. NB: If a particular file representation is in memory, subclasses should always return ``False`` -- there's no good reason to read from memory in chunks. """ return self.size > (chunk_size or self.DEFAULT_CHUNK_SIZE) # ... def open(self, mode=None): if not self.closed: self.seek(0) elif self.name and os.path.exists(self.name): self.file = open(self.name, mode or self.mode) else: raise ValueError("The file cannot be reopened.") return self def close(self): self.file.close()这里就能看到我们之前在实验1中用来保存上传文件时用到的 chunks() 方法,我们现在通过 Django 的命令行模式来使用下这个 File 类,看它有哪些功能。(django-manual) [root@server first_django_app]# python manage.py shellPython 3.8.1 (default, Dec 24 2019, 17:04:00) [GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linuxType "help", "copyright", "credits" or "license" for more information.(InteractiveConsole)>>> from django.core.files import File接下来,我们看到 File 类实例化时要关联一个文件对象,我们使用之前实验1上传的文件 upload.txt 作为实例化参数:>>> fp = open('/root/test/django/upload.txt', 'r+')>>> f = File(fp)接下来我们就可以测试 File 对象中的各种属性和方法了。具体操作如下:>>> f.name'/root/test/django/upload.txt'>>> f.size47# 按照20字节大小,判断文件需不需要分块读入>>> f.multiple_chunks(20)True# 默认块大小64k,47字节太小了,所以不用分块读入>>> f.multiple_chunks()False我们可以使用 chunks() 方法分块读取文件内容,然后做我们想做的事情,如下:>>> for c in f.chunks():... print('本次读入:{}'.format(c))... 本次读入:测试上传文件xxxxxspyinx test upload>>> for c in f.chunks(20):... print('本次读入:{}'.format(c))... 本次读入:测试上传文件xxxxxspyinx本次读入: test upload上面测试了2种形式,一种不需要分块读如数据,一口气读完所有内容(因为默认的分块大小大于文件内容)。另一种则设置小一些分块大小,这样会每次读取最多20字节内容,依次打印读取到的内容。接下来我们看下和上传相关的两个文件类:TemporaryUploadedFile 和 InMemoryUploadedFile。这两个类都是继承自 UploadedFile,而 UploadedFile 又是继承至 File 类的。# 源码路径: django/core/files/uploadedfile.pyclass UploadedFile(File): """ An abstract uploaded file (``TemporaryUploadedFile`` and ``InMemoryUploadedFile`` are the built-in concrete subclasses). An ``UploadedFile`` object behaves somewhat like a file object and represents some file data that the user submitted with a form. """ def __init__(self, file=None, name=None, content_type=None, size=None, charset=None, content_type_extra=None): super().__init__(file, name) self.size = size self.content_type = content_type self.charset = charset self.content_type_extra = content_type_extra def __repr__(self): return "<%s: %s (%s)>" % (self.__class__.__name__, self.name, self.content_type) def _get_name(self): return self._name def _set_name(self, name): # Sanitize the file name so that it can't be dangerous. if name is not None: # Just use the basename of the file -- anything else is dangerous. name = os.path.basename(name) # File names longer than 255 characters can cause problems on older OSes. if len(name) > 255: name, ext = os.path.splitext(name) ext = ext[:255] name = name[:255 - len(ext)] + ext self._name = name name = property(_get_name, _set_name)这个类相比于 File 基类主要是增加了多个实例属性,其他方法到没啥变化。接下里来看继承这个类的两个 File 类:class TemporaryUploadedFile(UploadedFile): """ A file uploaded to a temporary location (i.e. stream-to-disk). """ def __init__(self, name, content_type, size, charset, content_type_extra=None): _, ext = os.path.splitext(name) file = tempfile.NamedTemporaryFile(suffix='.upload' + ext, dir=settings.FILE_UPLOAD_TEMP_DIR) super().__init__(file, name, content_type, size, charset, content_type_extra) def temporary_file_path(self): """Return the full path of this file.""" return self.file.name def close(self): try: return self.file.close() except FileNotFoundError: # The file was moved or deleted before the tempfile could unlink # it. Still sets self.file.close_called and calls # self.file.file.close() before the exception. passclass InMemoryUploadedFile(UploadedFile): """ A file uploaded into memory (i.e. stream-to-memory). """ def __init__(self, file, field_name, name, content_type, size, charset, content_type_extra=None): super().__init__(file, name, content_type, size, charset, content_type_extra) self.field_name = field_name def open(self, mode=None): self.file.seek(0) return self def chunks(self, chunk_size=None): self.file.seek(0) yield self.read() def multiple_chunks(self, chunk_size=None): # Since it's in memory, we'll never have multiple chunks. return False这两段代码非常简单,代码展现的逻辑也非常清晰。TemporaryUploadedFile 打开的文件是临时生成的文件,而 InMemoryUploadedFile 类对于上传的文件会保存到内存中。我们熟悉了这两个类之后来对应的处理上传文件的 Handler,一个会使用 TemporaryUploadedFile 类使用临时文件保存上传的文件,另一个会使用 InMemoryUploadedFile 将上传文件的内容写到内存中:class TemporaryFileUploadHandler(FileUploadHandler): """ Upload handler that streams data into a temporary file. """ def new_file(self, *args, **kwargs): """ Create the file object to append to as data is coming in. """ super().new_file(*args, **kwargs) # 这个文件是打开临时文件的句柄 self.file = TemporaryUploadedFile(self.file_name, self.content_type, 0, self.charset, self.content_type_extra) # 将受到的数据写入到对应的临时文件中 def receive_data_chunk(self, raw_data, start): self.file.write(raw_data) # 处理文件完毕 def file_complete(self, file_size): # 文件指针,指向初始位置 self.file.seek(0) # 设置文件大小 self.file.size = file_size return self.fileclass MemoryFileUploadHandler(FileUploadHandler): """ File upload handler to stream uploads into memory (used for small files). """ def handle_raw_input(self, input_data, META, content_length, boundary, encoding=None): """ Use the content_length to signal whether or not this handler should be used. """ # Check the content-length header to see if we should # If the post is too large, we cannot use the Memory handler. self.activated = content_length <= settings.FILE_UPLOAD_MAX_MEMORY_SIZE def new_file(self, *args, **kwargs): super().new_file(*args, **kwargs) if self.activated: self.file = BytesIO() raise StopFutureHandlers() def receive_data_chunk(self, raw_data, start): """Add the data to the BytesIO file.""" if self.activated: self.file.write(raw_data) else: return raw_data def file_complete(self, file_size): """Return a file object if this handler is activated.""" if not self.activated: return self.file.seek(0) return InMemoryUploadedFile( file=self.file, field_name=self.field_name, name=self.file_name, content_type=self.content_type, size=file_size, charset=self.charset, content_type_extra=self.content_type_extra )
- 3.如何在已有的项目中集成Flutter 移动端架构师电子书
- Hystrix 配置项讲解(二) 还不会 Hystrix ?那就赶快来学习吧!
tell相关搜索
-
tab
table
tableau
tablelayout
table样式
taif
tail
talk
tamcat
tan
target属性
task
tbody
tcl tk
TCP IP
tcp ip协议
tcpdump
tcpip
tcpip协议
tcp连接