1.3 Caching, Verification Code, Logon, Form Verification
Caching in Django
-
Interface and usage
from django.core.cache import cache # Set age = 123, 10 seconds expiration in the cache cache.set('age', 123, 10) # Get age a = cache.get('age') print(a) # Self increment x = cache.incr('age') print(x)
-
Using Redis as the Cache Backend
-
Install pip install django-redis
-
settings configuration
CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/0", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "PICKLE_VERSION": -1, } } }
-
-
The expiration time can be used to process some temporary data with time-invalidation, such as mobile phone verification code.
-
Interview questions:
- How to use Redis as a cache?
Analysis of Cookie and Session Mechanism
-
Review of HTTP Protocol
- host
- linux: /etc/hosts
- windows: C:/Windows/System32/drivers/etc/hosts
- host
-
Generation process
- Browser: Send requests to the server
- Server: Accept and create a session object (which contains a session_id)
- Server: Execute the views function and get a response object
- Server: Execute response.set_cookie('session id', session_id) to write session_id to cookie
- Server: Return response to browser
- Browser: Read the response message, take session_id from Cookies and save it
-
Follow-up requests
- Browser: Send requests to the server, session_id with Cookies to Server
- Server: Extract session_id from Headers Cookies
- Server: Find the corresponding data according to session_id and confirm the identity of the client
-
Code Implementation in Django
class SessionMiddleware(MiddlewareMixin): def __init__(self, get_response=None): self.get_response = get_response engine = import_module(settings.SESSION_ENGINE) self.SessionStore = engine.SessionStore # Setting Session Storage Class def process_request(self, request): # Getting session ID from Cookie session_key = request.COOKIES.get('session_id') # Get previously saved data through session_key request.session = self.SessionStore(session_key) def process_response(self, request, response): try: # After the View function finishes, get the session status accessed = request.session.accessed modified = request.session.modified empty = request.session.is_empty() except AttributeError: pass else: # If there is a session ID in the Cookie, but the session is empty, # Explain that session.flush and other operations have been performed in view. # Delete session directly from Cookie if 'session_id' in request.COOKIES and empty: response.delete_cookie( settings.SESSION_COOKIE_NAME, path=settings.SESSION_COOKIE_PATH, domain=settings.SESSION_COOKIE_DOMAIN, ) else: if accessed: patch_vary_headers(response, ('Cookie',)) if (modified or settings.SESSION_SAVE_EVERY_REQUEST) and not empty: # Set expiration time if request.session.get_expire_at_browser_close(): max_age = None expires = None else: max_age = request.session.get_expiry_age() expires_time = time.time() + max_age expires = cookie_date(expires_time) # Save session data and refresh client Cookie if response.status_code != 500: try: request.session.save() except UpdateError: raise SuspiciousOperation( "The request's session was deleted before the " "request completed. The user may have logged " "out in a concurrent request, for example." ) # Let client add session ID to Cookie response.set_cookie( 'session_id', request.session.session_key, max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN, path=settings.SESSION_COOKIE_PATH, secure=settings.SESSION_COOKIE_SECURE or None, httponly=settings.SESSION_COOKIE_HTTPONLY or None, ) return response
-
Interview questions:
- How to distinguish Cookie from Session?
- Describe the HTTP protocol
Verify SMS
- Adding new url routing mapping to urls.py
- url(r'api/user/submit/vcode', user_api.submit_vcode)
- Implement routing mapping:
- submit_vcode
- Get the mobile phone number, authentication code
- Remove the validation code corresponding to this phone number from the cache
- Check the validation code for consistency, login or automatic registration
- Inconsistent return error
- submit_vcode
Personal Data Interface Planning
- Access to Personal Data Interface
- Modifying Personal Data Interface
- Upload Personal Portrait Interface
Profile model design (for reference only)
Field | Description |
---|---|
location | Target City |
min_distance | Minimum search range |
max_distance | Maximum search range |
min_dating_age | Minimum dating age |
max_dating_age | Maximum dating age |
dating_sex | Matched sex |
vibration | Open vibration |
only_matche | Don't let me see my album for matching people |
auto_play | Auto Play Video |
Difficulties in Development
- What is the relationship between Profile and User?
- How to build "table association" without using foreign keys in an enterprise?
- How should I verify that there are too many fields in the interface for bulk submission?
- How to upload the avatar? https://docs.djangoproject.com/zh-hans/2.0/topics/http/file-uploads/
- How to save a large number of static files in a large project?
- How can slow operations such as uploading files, sending validation codes and image processing be handled to shorten the waiting time of users?
Construction of Database Table Relations
-
Relational Classification
- One-to-one relationship
- One-to-many relationship
- Many-to-many relationship
-
Advantages and disadvantages of foreign keys
- Advantage:
- Data consistency and integrity are guaranteed by the database itself, and the data is more reliable.
- Can increase the readability of ER graphs
- Foreign keys can save development
- Disadvantages:
- Performance flaws with additional overhead
- When the primary key table is locked, the table corresponding to the foreign key is also locked.
- When deleting the data of the primary key table, the data of the foreign key table should be deleted first.
- When modifying foreign key table fields, foreign key constraints need to be reconstructed
- Can't be used in Distributed Environments
- It's not easy to decouple data
- Advantage:
-
Application scenarios
- Scenario: Internal systems, traditional enterprise applications can be used (data volume is controllable, database server number is controllable)
- Not applicable scenario: Internet industry is not recommended to use
-
Manually build associations
- One-to-one: the main table id corresponds to the sub-table id exactly one-to-one
- One-to-many: Add the unique table id field to the "many" table
- Many-to-many: Create relational tables in which only the IDs of two associated entries are stored
- Reflections on Blog Cases
- The relationship between user and text: one-to-many
- User-Collection Relations: Many-to-Many
- User-role-permission relationship
- User-role: one-to-many
2. Role-permission: many-to-many
-
Subtables can be associated by property
-
property usage
class Box: def __init__(self): self.l = 123 self.w = 10 self.h = 80 @property def V(self): return self.l * self.w * self.h b = Box() print(b.V)
-
Association operations on subtables
class User(models.Model): ... user_id = models.IntergerField() ... @property def user_profile(self): if not hasattr(self, '_profile'): self._profile = Profile.objects.get(user_id=self.user_id) return self._profile class User(models.Model): ... demo_id = models.IntegerField() ... @property def demo(self): if not hasattr(self, '_demo'): self._demo = Demo.objects.get(id=self.demo_id) return self._demo
class Demo(models.Model):
xxx = models.CharField()
yyy = models.CharField()user = User.objects.get(id=123)
print(user.demo.xxx)
print(user.demo.yyy)
```-
Attribute values can also be cached using cached_property
from django.utils.functional import cached_property class User(models.Model): year = 1990 month = 10 day = 29 @cached_property def age(self): today = datetime.date.today() birth_date = datetime.date(self.year, self.month, self.day) times = today - birth_date return times.days // 365
-
- Interview questions:
- Complex SQL Queries: Grouping, Connecting
- The Student table has: id and name fields
- Score tables are: student_id, exam_id, object_id, score
- Ask:
- The best student in an exam
- Advanced thinking: the top three students in each exam?
- Tip: Window function.
- Complex SQL Queries: Grouping, Connecting
Form form validation in Django
-
Django Form Core Function: Data Validation
-
The < form > tab in the web page
- The method of the < form > tag can only be POST or GET
- When method=POST, the form data is in the body part of the request
- When method=GET, form data appears in the URL
-
Properties and Methods of Form Objects
- form.is_valid(): form validation
- form.has_changed(): Check for modifications
- Form. clean < field > (): Special cleaning and validation for a field
- Form. cleaned_data ['field name']: The cleaned data is stored in this property
-
Definition and use of Form
from django import forms class TestForm(forms.Form): TAGS = ( ('py', 'python'), ('ln', 'linux'), ('dj', 'django'), ) fid = forms.IntegerField() name = forms.CharField(max_length=10) tag = forms.ChoiceField(choices=TAGS) date = forms.DateField() POST = {'fid': 'bear', 'name': 'hello-1234567890', 'tag': 'django', 'date': '2017/12/17'} form = TestForm(POST) print(form.is_valid()) print(form.cleaned_data) # The cleaned_data attribute is added dynamically when the is_valid function is executed print(form.errors)
-
Model Form can be created from the corresponding Models
class UserForm(ModelForm): class Meta: model = User fields = ['name', 'birth']
Cloud Service Market
-
AWS: Amazon: Amazon Web Service, the world leader
- Cloud server: EC2: elastic cloud computer
- Cloud Storage: S3: simple storage service
- Cloud database: RDS: relationship database service: MySQL
- Message queue: SQS: Simple Queue Service
- Full-text retrieval:
- Cloud Data Warehouse: redshift
- Azure: Microsoft: There are a lot of linux servers, all kinds of services.
- Google Cloud
-
Ali Yun: First in China
- Cloud Server: ECS
- Cloud Storage: OSS
- Cloud database: RDS
- Tencent Cloud
- ...
- Not worth mentioning cloud:
- Jinshan Cloud
- Baidu Cloud
- Huaweiyun
- Special Cloud:
- Storage:
- Seven oxen
- Picture zooming:
- New Picture Style
- Choose the scaling method you want
- give a name
- Preservation
- Usage method:
- http://pvhv7tfry.bkt.clouddn.com/space_city.jpg?imageView2/1/w/200/h/200/q/75|imageslim
- Gradual display of pictures:
1.
- Picture zooming:
- Shoot again
- Seven oxen
- Live broadcast:
- Short Message: Cloud News
- E-mail: sendcloud
- Storage:
- How to build services after going to the cloud:
- Only use cloud servers, others are implemented in the cloud servers themselves.
- Dependent on the cloud, the cost of changing or leaving the cloud is extremely low
- More people and longer development cycle
- Make full use of all kinds of cloud services
- Saving manpower cost, using fewer people and short development cycle
- Depending on cloud services, the cost of changing or leaving the cloud is high
- Make High Availability on Cloud
- Only use cloud servers, others are implemented in the cloud servers themselves.
- Not in the clouds,
- Traditional Business
- Pure Traffic Service: Video Distribution
- Interview questions:
- What cloud services do you use?
- What functions are used?
- How much?